javascript 在 A-tag 中触发 Click 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12948736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fire Click event in A-tag
提问by Habeeb Perwad
Possible Duplicate:
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?
可能的重复:
如果我还没有使用 bind 或 click 将事件处理程序绑定到它,我可以调用 jquery click() 来跟随 <a> 链接吗?
I wrote the following code.
我写了以下代码。
<div style="background-color:orange">Click me to open the link
<br>
<a target="_blank" href="http://example.com">Link</a>
</div>
<script>
jQuery('div').click(function(){
jQuery('a').click();
});
jQuery('a').click(function(e){
alert('It came here!');
e.stopPropagation();
return true;
});
</script>
But the link is not opening.
但是链接打不开。
UPDATE: added target attribute to A-tag.
更新:向 A 标签添加了目标属性。
采纳答案by Lix
First of all, you are using a selector that will match all<a>
tags on your page. Perhaps you want to give your <a>
an id attribute so that you can target one specific element...
首先,您使用的选择器将匹配您页面上的所有<a>
标签。也许你想给你<a>
的 id 属性,以便你可以定位一个特定的元素......
<a href="foobar.html" id="foo">foo</a>
You could also try use the trigger
function to simulate a click on the element -
您也可以尝试使用该trigger
功能来模拟对元素的点击 -
$('#foo').trigger('click');
One last thing to mention is that you didn't actually call the method to open the link. You can try use this code -
最后要提到的一件事是,您实际上并未调用打开链接的方法。您可以尝试使用此代码 -
jQuery('a').click(function(e){
alert('It came here!');
window.open($(this).attr('href'));
return false;
});
Reference -
参考 -
Description:Execute all handlers and behaviors attached to the matched elements for the given event type.
描述:执行附加到给定事件类型的匹配元素的所有处理程序和行为。
回答by karaxuna
<div style="background-color:orange">Click me to open the link
<br>
<a id="b" href="http://example.com">Link</a>
</div>
jQuery('div').click(function(){
document.getElementById('b').click();
});
fiddle: http://jsfiddle.net/zZqQs/4/
小提琴:http: //jsfiddle.net/zZqQs/4/
OR:
或者:
jQuery('a')[0].click();
Appears that jquery click and raw JS click differs from each other.
看起来 jquery click 和 raw JS click 彼此不同。
回答by ARUNRAJ
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<div style="background-color:orange">Click me to open the link
<br>
<a href="http://example.com" target="_blank">Link</a>
</div>
<script>
$('div').click(function () {
$('a').click();
});
$('a').click(function (e) {
alert('It came here!');
e.stopPropagation();
window.location = $("a").attr("href");
return true;
});
</script>