簡體   English   中英

如何防止子事件在JQuery中觸發

[英]How to prevent child event from firing in JQuery

所以我有一個按鈕

<input id="expandButton" type="submit" value="Expand" class="loadWindow"/>

我有兩個事件處理程序附加。

function confirmContinue() {
     return confirm("Do you want to expand window, might reload some information?");
}

$("input.loadWindow").click(function(event) {
      showProcessingWindow(event);
}

$("#expandButton").click(function(event) {
     var result = confirmContinue();
     if (!result) {
          event.preventDefault();
          event.stopPropagaton();
     }
}

如果要說“取消”,我想防止觸發“ input.loadWindow” click事件。

這就是現在正在發生的事情。 單擊按鈕->確認觸發->我單擊取消->顯示處理窗口仍觸發。

我想要按鈕單擊->確認觸發->我單擊取消->不執行任何操作。

看起來event.stopImmediatePropagation()在這種情況下可以工作。

$("#expandButton").click(function(event) {
     var result = confirmContinue();
     if (!result) {
          event.preventDefault();
          event.stopImmediatePropagation(); 
     }
}

小提琴演示-http: //jsfiddle.net/w2vwn35x/1/

嘗試這個:

 $("#expandButton").click(function(event) { if(confirm('Do you want to expand window, might reload some information?')){ // call your function here }else{ return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="expandButton" type="submit" value="Expand" class="loadWindow"/> 

或者,使用標志。

var doShowWindow = true;
$("#expandButton").click(function(event) {
    var result = confirmContinue();
    if (!result) {
        doShowWindow = false;
    }
});

$("input.loadWindow").click(function(event) {
    if(doShowWindow){  
        alert(1);
    }
    doShowWindow = true;
});

這是一個小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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