jQuery触发click vs click()? [英] jQuery trigger click vs click ()?
问题描述
我有这么简单的代码: 此处
I have this simple code : here
$(".btn").on('click',function () {
$(".a").trigger('click');
});
$(".btn2").on('click',function () {
$(".a")[0].click();
});
我正在尝试模拟按下Anchor。
I'm trying to simulate pressing on Anchor.
但是当我使用jQuery的触发器
时,它不起作用(为什么?)
But when I use jQuery's trigger
, it doesn't work (why?)
当我使用jsobj.click()
func,它确实有用。
When I use "jsobj".click()
func, it does work.
阅读完jQuery文档后,我不知道看不出有什么原因。
After reading the jQuery documentation, I don't see any reason why it shouldn't.
帮助?
PS:我正在使用Chrome 。
PS: I'm using Chrome.
推荐答案
实际上 $(。a)。触发器('click');
触发click事件,但这并不意味着它会点击链接,而是如果你已经拥有一个,它将执行事件处理程序,即
Actually $(".a").trigger('click');
triggers the click event but it doesn't mean that it'll click the link, instead it'll execute the event handler if you already have one, i.e.
$(".btn, .btn2").on('click',function () {
$($(".a")[0]).trigger('click'); // first element
});
$(".a").on('click', function (e){
alert(e.target);
});
给定的示例将触发 a
的点击事件,将使用
The given example will trigger the click event of the a
and will execute the handler (the anonymous function) that's already have been registered for that event using
$(".a").on('click', function (e){...});
这篇关于jQuery触发click vs click()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!