javascript stoppropagation 不适用于 ajax .load
当点击 时,我使用
.stopPropagataion()
来停止 中的冒泡标签。
$(document).ready(function(){
$(".article a").click(function(e) {
e.stopPropagation();
});
});
使用此 HTML:
<li class="article" onlick="javascript:somefunction();">
<div id="div_id">
<a>Some link</a>
</div>
</li>
一切正常,但随后我使用 $('#div_id').load("div_html.html")
将一些内容动态加载到 div 中。现在我的 .stopPropagation()
不会停止冒泡。为什么它不再起作用了?
I used .stopPropagataion()
to stop the bubbling in <li class="article">
when clicking on the <a>
tag.
$(document).ready(function(){
$(".article a").click(function(e) {
e.stopPropagation();
});
});
With this HTML:
<li class="article" onlick="javascript:somefunction();">
<div id="div_id">
<a>Some link</a>
</div>
</li>
Everything worked fine, but then I used $('#div_id').load("div_html.html")
to load some content into the div dynamically. Now my .stopPropagation()
doesn't stop the bubbling. Why isn't it working anymore?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,当您更新
div
的内容时,您会销毁其中的所有元素(包括附加到它们的任何事件处理程序)。您的代码正在将click
事件挂接到div
中的a
元素当您的代码运行时 ;div
中的新a
元素将不会被连接。在您的情况下,您最好使用
delegate
(delegate
="http://jsbin.com/abizew/2" rel="nofollow">实时示例,带有load
):挂钩
click
改为div
。当单击发生时,它会从链接冒泡到div
,其中 jQuery 创建的单击处理程序会检查它以查看它是否实际上是对任何a
元素的单击。如果是这样,它将停止点击。从 jQuery 1.7 开始,新的推荐语法是
on
:请注意参数的顺序与
delegate
不同,但除此之外它做同样的事情。我建议避免将旧式 DOM0 处理程序(事件处理程序属性)与新式 DOM2 代码(附加了 jQuery 的处理程序)相结合。在许多浏览器中,这两种机制有些独立,并且可能无法像您希望的那样很好地协同工作。
对此还有另外两条评论:
onclick
,而不是onlick
(您缺少c
)javascript :
事件处理程序属性上的伪协议,仅href
。只需删除该部分即可。 (为什么它不会导致错误?因为纯粹是巧合,它是有效的 JavaScript - 您正在定义一个标签 你从未使用过。)The problem is that when you update the content of the
div
, you destroy all of the elements that were inside it (including any event handlers attached to them). Your code is hooking theclick
event on thea
elements that are in thediv
as of when your code runs; newa
elements in thediv
will not be hooked up.In your case, you're better off using
delegate
(live example, withload
):That hooks
click
on thediv
instead. When the click occurs, it bubbles from the link to thediv
, where the click handler created by jQuery examines it to see if it was actually a click on anya
element. If so, it stops the click.As of jQuery 1.7, the new recommended syntax is
on
instead:Note that the order of arguments is different from
delegate
, but other than that it does the same thing.I'd recommend avoiding combining old-style DOM0 handlers (event handler attributes) with new-style DOM2 code (your handler attached with jQuery). In many browsers, the two mechanisms are somewhat separate and may not play as nicely together as you'd like.
Two other comments on this:
onclick
, notonlick
(you're missing thec
)javascript:
pseudo-protocol on event handler attributes, onlyhref
s. Just remove that part. (Why doesn't it cause an error? Because purely by coincidence, it's valid JavaScript — you're defining a label you never use.)