gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:52:47 30 4
gpt4 key购买 nike

我有一个 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com