【问题标题】:How to have jQuery fired exact binded event only如何让 jQuery 只触发精确绑定的事件
【发布时间】:2012-07-10 14:51:07
【问题描述】:

我有一个场景,我必须将点击事件绑定到外部和内部 div,但是我点击内部 div 会触发 2 个点击事件,包括外部和内部 div 绑定事件。

如何只为内部 div 触发确切的事件?

这里我附上了 jsfiddle 演示:

http://jsfiddle.net/mochatony/FkCmH/8/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以使用.stopPropagation 方法防止事件冒泡到父级,正如其名称所暗示的那样。更新链接:http://jsfiddle.net/EQpA2/

    $('#big-box').click(function(){
        console.log('blue box');     
    });
    
    $('#small-box').click(function(e){
        e.stopPropagation();
        console.log('red box');     
    });
    

    【讨论】:

      【解决方案2】:

      只需将return false; 添加到小盒子处理程序即可。

      已修复 jsFiddle:http://jsfiddle.net/brodenbaugh/BMPYd/

      $('#small-box').click(function(){
          console.log('red box');
          return false;
      });
      

      【讨论】:

        猜你喜欢
        • 2013-10-08
        • 1970-01-01
        • 1970-01-01
        • 2014-07-28
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 2018-08-01
        • 2018-08-31
        相关资源
        最近更新 更多