5

这是问题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链接时,它应该只打开灯箱弹出窗口(它确实如此),但内联 onclickli也会触发。问题是这些li标签都是一些部分的一部分,这些部分是通过不同页面上的 ajax 获取的。所以我使用 jQuerydelegate来绑定事件,如下所示:

$('#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()但没有成功。我在这里缺少什么吗?

4

4 回答 4

4

AFAIK 您无法通过停止附加事件处理程序中的冒泡来可靠地阻止内联事件处理程序触发。

此外,使用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'); 

参考:.delegate()

于 2010-08-18T05:52:53.373 回答
0

你能试试这个吗?

$('#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;
});
于 2010-08-18T05:55:36.020 回答
0

你可以试试这个,因为.delegate()已经被这个.on()方法取代了。

它会正常工作

于 2012-10-18T08:02:08.263 回答
0
 $('#update-list').delegate('.popup-link', 'click', function(e){       
  e.stopImmediatePropagation();
  e.preventDefault();
  // do something...
});
于 2016-01-03T15:21:07.840 回答