【问题标题】:How to prevent child event from firing in JQuery如何防止在 JQuery 中触发子事件
【发布时间】:2015-07-01 21:33:32
【问题描述】:

所以我有一个按钮

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

这就是现在正在发生的事情。 单击按钮--> 确认触发--> 我单击取消--> 显示处理窗口仍然触发。

我想要这样 单击按钮->确认触发->我单击取消->什么也不做。

【问题讨论】:

  • 为什么同一元素有两个独立的事件处理程序?这样会使事情复杂化。如果您只想显示特定 ID 的确认信息,可以使用 $(this).attr("id") 检查当前点击事件的 ID
  • 脚本位于两个不同的文件中。一个脚本 loadWindow 在所有页面中。另一个仅特定于某些页面。
  • 好的。知道了。我已经发布了答案。在这种情况下应该可以工作

标签: javascript jquery events chaining preventdefault


【解决方案1】:

看起来 event.stopImmediatePropagation() 在这种情况下可以工作。

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

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      【解决方案3】:

      或者,使用标志。

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 2014-09-17
        • 1970-01-01
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多