[英]JQuery.live() not working properly
我知道live
在1.7版中已弃用,而在1.9版中已删除,因此不再建议使用。 但尽管如此,因为我准备采访机考,所以我试图让之间的差异live
和on
。 文件说
在事件处理程序中调用event.stopPropagation()不能有效地停止附加在文档下方的事件处理程序。 该事件已传播到文档。
因此我尝试了这个。 标记:
<div>
<h1>
<a href="#">
<span>Hello</span>
</a>
</h1>
</div>
脚本:
$(document).ready(function () {
$('span').live("click",function () {
alert('span');
});
$('a').click(function () {
alert('span a');
});
$('h1').click(function () {
alert('span a h1');
event.stopPropagation();
});
$('div').click(function () {
alert('span a h1 div');
});
});
我使用jQuery 1.7版本,其中两个live
和on
存在。
发生了什么:
live
跨度是没有得到调用,而不是它调用直接click
的a
。 live
以外的所有其他事件,那么它将被调用。 event.stopPropagation();
它将停止事件冒泡event.stopPropagation();
live
附加的事件处理程序始终附加到document
。 如果在live
回调中调用event.stopPropagation
,则此事件已经冒泡到文档中,因此对直接附加的事件处理程序无效。
当事件到达h1
元素时,将调用event.stopPropagation()
,因此它将永远不会到达附加了live
事件处理程序的document
。
使用on
可以创建jQuery支持的所有类型的事件处理。 如果您查看jQuery的源代码,则可以在1.7中看到live
函数仅映射到on:
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
}
删除live
的原因是为了使API更清晰,更合乎逻辑,以便了解事件何时发生以及在何处被捕获。
编辑
您的DOM和事件处理程序的附加位置:
document $('span').live("click") **not called** (equal to: $(document).on('click', 'span') )
|
div $('div').click() **not called**
|
h1 $('h1').click() + event.stopPropagation() **the propagation (bubbling) is stopped here not reaching the document**
|
a $('a').click()
|
span **event happens here and bubbles up**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.