[英]Stop propagation with jquery delegate/live function not working
继承人问题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()
但没有成功。 这里有什么我想念的吗?
AFAIK您无法通过停止附加事件处理程序中的冒泡来可靠地阻止内联事件处理程序触发。
此外,使用live()
或.delegate()
不能使用preventDefault()
或stopPropagation()
。 您需要返回false以防止冒泡阶段和默认行为。
无论如何,正如我已经提到的那样,你无法阻止内联事件处理程序触发。
所以,要么创建它完全unobtrusive
(这是我强烈推荐的)或删除代码中的内联单击处理程序 。
例:
$('#update-list').delegate('.popup-link', 'click', function(e){
$.popup(); // launch popup
return false;
}).delegate('.update', 'click', function(){
window.location('some_url');
})
// the rest of this is unnecessary if you can just omit the onclick attribute
.find('.update')
.removeAttr('onclick');
参考: .delegate()
$('#update-list').delegate('.popup-link', 'click', function(e){
e.stopImmediatePropagation();
e.preventDefault();
// do something...
});
你能试试吗?
$('#update-list').delegate('.popup-link', 'click', function(e){
// e.target is <span> while e.currentTarget is .popup-link
e.stopPropagation();
e.preventDefault(); // or return false
// open popup in a timeout so that this function can return false
window.setTimeout(function() {$.popup();}, 20);
// for IE
e.cancelBubble = true;
return false;
});
您可以尝试这样做.delegate()
已被.on()
方法取代。
它会工作正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.