使用jquery delegate/live函数停止传播不起作用

fen*_*yer 5 javascript jquery delegation javascript-events

继承人问题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>
Run Code Online (Sandbox Code Playgroud)

当我点击.popup-link链接时,它应该只打开灯箱弹出窗口(它确实如此),但是内联onclick li也会触发.问题是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
});
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用,内联onclick无论如何都会触发.我也试过live()但没有成功.这里有什么我想念的吗?

jAn*_*ndy 4

据我所知,您无法通过停止附加事件处理程序内的冒泡来可靠地防止内联事件处理程序触发。

此外,使用live()or.delegate()不能使用preventDefault()nor 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'); 
Run Code Online (Sandbox Code Playgroud)

参考:.delegate()