jQuery .trigger 不会在输入按键时触发

jQuery .trigger doesn't fire on enter keystroke

我正在尝试创建一个 html 和 jQuery 菜单,该菜单使用箭头键进行导航,并使用进入按钮 "click" 和所述菜单中的 link。

我创建了一个 fiddle and the menu is live on the homepage of my website 但这是菜单 HTML:

<ul id="home_menu">
        <li class="arrow-link"><a href="/blog/">Blog</a></li>
        <li><a href="/resume/">Resume</a></li>
        <li><a href="/portfolio/">Portfolio</a></li>
        <li><a href="/tools">Tutorials</a></li>
        <li><a href="/contact/">Contact</a></li>
    </ul>

这里是 .arrow-link class:

.arrow-link{
   background: url(media/images/selectArrow.png) no-repeat;
   background-position: 0 3px;
}

如果您查看控制台,您会看到我正在记录两个变量,位置计数器,它指示 <li> 元素 .arrow-link class 被应用到(见下面的脚本),并且 击键值 ,这是不言自明的。

我创建了一个非常简单的脚本,它只是根据 Position Counter 值切换 .arrow-link class:

var pos = 1;

        jQuery(document).keydown(function (e) {

            switch (e.which) {

                case 38: // up

                    pos--;

                    if (pos > 5) {
                        pos = 1;
                    } else if (pos < 1) {
                        pos = 5;
                    }

                    moveArrow(pos, e.which);

                    break;

                case 40: // down

                    pos++;

                    if (pos > 5) {
                        pos = 1;
                    } else if (pos < 1) {
                        pos = 5;
                    }

                    moveArrow(pos, e.which);

                    break;

                case 13: // enter

                    console.log("Keystroke Value: " + e.which + " (Enter)");
                    jQuery('.arrow-link a').trigger("click");

                    break;


                default:
                    return; // exit this handler for other keys
            }
            e.preventDefault(); // prevent the default action (scroll / move caret)
        });

        function moveArrow(pos, e) {

            console.log("Position counter: " + pos);
            console.log("Keystroke Value: " + e);
            jQuery("#home_menu").children().removeClass("arrow-link");
            jQuery("#home_menu li:nth-child(" + pos + ")").addClass("arrow-link");

        }

所以从这个脚本我知道传递给 case 语句的值是正确的,我可以在按下回车按钮后生成输出到控制台,但是,在我尝试模拟点击的那一行 ( jQuery('.arrow-link a').trigger("click");), 没有任何反应。我在控制台中没有看到任何错误,它只是什么也没做。

我也尝试过使用 (".arrow-link a").click(); 而不是 jQuery('.arrow-link a').trigger("click"); 但是还是不行。

我需要在那里使用什么才能将用户带到相应的link?

即使在 'a' 元素上触发点击在 jQuery 中也不起作用,但是,您可以简单地使用原版 javascript:

document.querySelector('.arrow-link a').click();

您可以在此处看到有效的 fiddle:JSFiddle

这与此处的问题类似:Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?