如何防止在JQuery中触发子事件

时间:2015-07-01 21:33:33

标签: javascript jquery events chaining preventdefault

所以我有一个按钮

<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”点击事件。

这就是现在正在发生的事情。 单击按钮 - &gt;确认火灾 - &gt;我点击取消 - &gt;显示处理窗口仍然会触发。

我想这样 单击按钮 - &gt;确认火灾 - &gt;我点击取消 - &gt;没做什么。

3 个答案:

答案 0 :(得分:2)

在这种情况下, event.stopImmediatePropagation() 似乎有用。

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

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

答案 1 :(得分:0)

试试这个:

$("#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"/>

答案 2 :(得分:0)

或者,使用旗帜。

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;
});

Here's a fiddle

相关问题