【发布时间】:2018-10-13 22:08:24
【问题描述】:
我正在使用以下 Vanilla 绑定来模拟 jQuery 委托事件:
document.addEventListener('click', function(e) {
console.log("some element was clicked");
console.log(e.target);
//here's where I would filter by target
});
除了我尝试使用 jQuery 触发链接元素 <a href="#"> 上的单击事件外,一切正常。然后它根本不起作用。普通点击事件处理程序不会被触发。
Reproduction working on <b> element
$('button').click(function() {
$('ul').append('<li><b>New</b></li>');
});
document.addEventListener('click', function(e) {
console.log("some element was clicked");
console.log(e.target);
});
$(document).on('keydown', function(){
console.warn("-------Trigger--------")
$('li').find('b').trigger('click');
});
div{
background: yellow;
padding:10px 20px;
border: 1px solid #ccc;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add element</button>
<span id="trigger">Trigger</span>
<div>
Just focus the white panel and press any key. That will trigger the jQuery.click() event as you can see in the code.
</div>
<ul>
<li>Old element</li>
<li>Old element</li>
<li><b>Old element</b></li>
</ul>
相反,如果我将链接元素替换为粗体<b>,它将按预期工作。
这是怎么回事?
Reproduction not working on <a> element
$('button').click(function() {
$('ul').append('<li><a href="#">New</a></li>');
});
document.addEventListener('click', function(e) {
console.log("some element was clicked");
console.log(e.target);
});
$(document).on('keydown', function(){
console.warn("-------Trigger--------")
$('li').find('a').trigger('click');
});
div{
background: yellow;
padding:10px 20px;
border: 1px solid #ccc;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add element</button>
<span id="trigger">Trigger</span>
<div>
Just focus the white panel and press any key. That will trigger the jQuery.click() event as you can see in the code.
</div>
<ul>
<li>Old element</li>
<li>Old element</li>
<li><a href="#">Old element</a></li>
</ul>
不,我不想像这样使用[0]:
$('li').find('a')[0].click();
我希望它正常触发:
$('li').find('a').click();
【问题讨论】:
-
我想
<form>也会失败? -
你是说
$(document).on('keydown', function(){不会触发点击? -
@Huangism nop,这是香草
$('li').find('a').trigger('click');没有捕捉到的东西。我已将问题更新为更清楚。 -
@Alvaro 是的,这就是我要问的,您必须将点击与 jquery 绑定才能触发它。在这里测试jsfiddle.net/s3q2q38z/5
-
@Huangism 你能解释一下为什么它在使用
b元素而不是a元素时可以正常工作$('li').find('a').trigger('click');
标签: javascript jquery jquery-3