javascript - 如何使用 JQuery 单击 anchor 以便 href 也被调用?

标签 javascript jquery html css ajax

我有一个 anchor 和一个文本框,如下所示:

 <div id="container">
        <input type="text" id="textBox" />       
        <a id="anchorTest" href="javascript: alert('inside anchorTest')">Click me</a>
    </div>

我正在尝试在单击回车键时将默认按钮设置为 anchor :

$(document).ready(function () {

            $('#anchorTest').click(function () {
                alert('clicked');
            });

            $('#container').keyup(function (e) {

                if (e.keyCode == 13) {                    
                    $('#anchorTest').triggerHandler('click');
                }
            });
        });

但是永远不会调用 anchor href javascript?

如何使用JQuery点击 anchor 让href也被调用?

我使用了下面的代码并且它有效但是有没有更好的方法来提交表单而我想要一个纯javascript代码:

window.location = $('#anchorTest').attr('href');   

谢谢

最佳答案

jQuery 以“特殊”方式处理 anchor 标记上的 click 事件。有关更多信息,请参阅此问题 - 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?

从上面的问题——

I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

关于javascript - 如何使用 JQuery 单击 anchor 以便 href 也被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7806493/

相关文章:

javascript - 开始日期不应大于结束日期 jquery php

javascript - 将焦点更改为溢出 :hidden contained element, 会移动它,但会导致这种差异不明显

html - 全宽透明文本区域输入

javascript - Socket.IO 接受不存在的 src 标签吗?

javascript - 对默认变量使用解构赋值和其余语法

javascript - 有没有办法断言在 Cypress 中没有调用路由?

javascript - - 已解决 - Javascript 'onMouseMove'/CSS :hover conflict

c# - 使用 jquery 超时 Ajax 请求?

javascript - 两列无序列表中不需要的间距

html - CocoonJS + Crafty 兼容性