当我使用 jQuery 动态创建一个 div,用它来包装另一个元素(使用 jQuery.wrap() 方法)并将一些事件绑定(bind)到包装器时,它们不会被触发。为什么?
看到这个 fiddle - http://jsfiddle.net/tqzzdu21/
var $wrapper = $('<div class="random-wrapper"></div>');
$('.random-element').wrap($wrapper);
$wrapper.click(function(){
alert('Sh*t happens ..');
});
只有委托(delegate)方法绑定(bind)的事件监听器才会被触发,但我不明白为什么它不应该触发直接绑定(bind)到元素实例的事件。
最佳答案
因为使用.wrap()在实际包装传递的元素之前创建它的克隆。因此,包装中使用的实际元素与传递的元素不同(在这种情况下,它不是由 $wrapper
引用的)。
相反,如果您访问目标元素的父元素并绑定(bind)事件,它应该可以工作
var $wrapper = $('<div class="random-wrapper"></div>');
$wrapper.click(function(){
alert('before wrap - wrapper click');
});
$('.random-element').wrap($wrapper);
$wrapper.click(function(){
alert('wrapper click');
});
$('.random-element').parent().click(function(){
alert('parent click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="random-element">Lipsum</div>
The .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.
关于jQuery - 元素在换行后不触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887201/