簡體   English   中英

使用jquery delegate / live函數停止傳播不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM