我有以下 html:
<ul id="contain">
<li class="active_one"></li>
<li class="two"></li>
</ul>
以及以下 jquery:
$contain = $('#contain'); //going to use a lot
$contain.on('click','li.two', function(){
console.log('working');
//plus do other stuff
});
以上不起作用,但是当我将其更改为:
$('body').on('click','li.two', function(){
console.log('working');
//plus do other stuff
});
然后它起作用了,但我知道最好的做法是尽可能靠近我尝试使用的父元素进行钻取,但每次我尝试这样做时,我显然做错了什么,因为我的父级选择器不起作用。
最佳答案
这意味着#contain
本身不是一个静态元素,您应该选择最接近该元素的static 父元素。否则 jQuery 不会选择元素并且委托(delegate)失败。
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
但是,如果该元素是静态的,则您选择该元素的时间过早,您应该等待 DOM 准备就绪。
$(document).ready(function(){
var $contain = $('#contain'); //going to use a lot
$contain.on('click','li.two', function(){
console.log('working');
//plus do other stuff
});
})
关于javascript - 为什么 jquery 事件委托(delegate)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14164296/