停止传播 jQuery 委托/实时功能不起作用
这是问题 html:
<ul id="update-list">
<li class="update" onclick="window.location('some_url')">
<h2> some header </h2>
<p> some paragraph </p>
<div>
<a class="popup-link">
<span> Show Popup </span>
<span> + </span>
</a>
</div>
</li>
// this repeats n times
//...
</ul>
当我单击 .popup-link
链接时,它应该仅打开灯箱弹出窗口(确实如此),但 li
上的内联 onclick 也会触发。问题是 li
标签都是某些部分的一部分,这些部分是通过不同页面上的 ajax 获取的。因此,我使用 jQuery 的 delegate
来绑定事件,如下所示:
$('#update-list').delegate('.popup-link', 'click', function(e){
// e.target is <span> while e.currentTarget is .popup-link
e.stopPropagation();
//console.log(e.isPropagationStopped()); this shows 'true' in console
$.popup(); // launch popup
e.preventDefault(); // or return false
});
这似乎不起作用,内联 onclick
无论如何都会触发。我也尝试过 live()
但没有成功。我在这里缺少什么吗?
Here's the problem html:
<ul id="update-list">
<li class="update" onclick="window.location('some_url')">
<h2> some header </h2>
<p> some paragraph </p>
<div>
<a class="popup-link">
<span> Show Popup </span>
<span> + </span>
</a>
</div>
</li>
// this repeats n times
//...
</ul>
When I click on .popup-link
link, it should open the lightbox popup only (which it does) but the inline onclick on li
also fires. The thing is that the li
tags are all part of some partial which is fetched via ajax on different pages. So I use jQuery's delegate
to bind the events as follows:
$('#update-list').delegate('.popup-link', 'click', function(e){
// e.target is <span> while e.currentTarget is .popup-link
e.stopPropagation();
//console.log(e.isPropagationStopped()); this shows 'true' in console
$.popup(); // launch popup
e.preventDefault(); // or return false
});
This doesn't seem to work and the inline onclick
fires anyway. I've tried with live()
as well but no success. Is there something I am missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,您无法通过停止附加事件处理程序内的冒泡来可靠地阻止内联事件处理程序触发。
此外,使用
live()
或.delegate()
时,您不能使用preventDefault()
或stopPropagation()
。您需要返回false以防止冒泡阶段和默认行为。无论如何,正如我已经提到的,您无法阻止内联事件处理程序随之触发。
因此,要么创建完全
不引人注目的
(这是我强烈推荐的),要么删除代码中的内联点击处理程序。示例:
参考:.delegate()
AFAIK you cannot reliably prevent an inline event handler from firing by stopping the bubbling within an attached event handler.
Furthermore, using
live()
or.delegate()
you cannot usepreventDefault()
norstopPropagation()
. You need to return false to prevent the bubble phase and the default behavior.Anyway, as I already mention you can't prevent the inline event handler to fire with that.
So either, create it completely
unobtrusive
(which is what I highly recommend) or remove that inline click handler in code.Example:
Ref.: .delegate()
你能试试这个吗?
Can you try this?
您可以尝试此操作,因为
.delegate()
已被.on()
方法取代。它会工作得很好
You can try this as
.delegate()
has been superseded by the.on()
method.It will work fine