【问题标题】:Trigger a hyperlink with keystroke用击键触发超链接
【发布时间】:2009-02-02 15:55:17
【问题描述】:

我想使用 jQuery 通过按 Enter 来触发超链接。我有以下 html,但 Enter-stroke 所做的只是触发警报,它不会导航到链接。但是,单击该链接会导航到新地址。我错过了什么?

我知道我的测试函数正在运行,因为 addClass/removeClass 函数正在运行。

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("a").click(function(event){
                alert(this.href);
            });
        });
        function test(event){
            if (event.keyCode == 13) {
                $("a").addClass("test");
                $("a.one").trigger('click');
            }
            else {
                $("a").removeClass("test");}
        }
    </script>
    <style type="text/css">
        a.test { font-weight: bold; }
    </style>
</head>
<body onkeypress='test(event)'>
    <a class="one" href="http://jquery.com/">jQuery</a>
    <br/>
    <a class="two" href="http://stackoverflow.com/">stack overflow</a>
</body>
</html>

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    添加一个 window.location = this.href;到您的点击功能。应该可以的。

    【讨论】:

      【解决方案2】:

      那么,您想触发点击还是简单地重新定位?链接本质上是重定位的,但是当您触发 onclick 到其他事件时,它只是执行绑定功能。

      我建议您将此任务分解为以下部分,以保持您的代码更简洁: 1) 单独的函数来执行所需的操作,包括使用 window.location.href="yournewurl" (或一些带有 jquery 插件的高级东西,如http://www.oakcitygraphics.com/jquery/jqURL/jqURLdemo.html)。 2) 在需要的事件上调用这个函数,比如 onclick 等。

      或者只是在 if (event.keyCode == 13) { ... } 块中强制定位。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多