如何在此代码中停止事件冒泡

How to stop event bubbling in this code?

本文关键字:事件 代码      更新时间:2023-09-26
$('#div1').on('click', '#otherDiv1', function(event){       
        //Show popup
        $('#popupDiv').bPopup({
            modalClose: false,
            follow: [false, false],
            closeClass: 'close'
        });             
        event.stopPropagation();
        $('#div2').on('click', '#otherDiv2', function (event) { 
             // here is ajax request         
            // close popup          
            $('#popupDiv').bPopup().close();
            event.stopPropagation();
        });
    }

多次点击 otherDiv2 调用 ajax 函数,我该如何停止?

网页代码

<div id="div2">
<div id="div1"><div id="otherDiv1">Click</div></div>
    <div id="popupDiv"><div class="close">X</div> 
        <input id="otherDiv2" name="otherDiv2" type="submit" value="Click" />   
    </div>
</div>

弹出 Div 是动态创建的

当我单击otherDviv1时,弹出窗口已打开,里面是一个用于ajax请求的按钮。当我单击按钮时,会调用一个请求并关闭弹出窗口。如果我再单击一次 otherDiv1 并按下按钮,请求将被调用两次,依此类推。

谢谢

没有必要

在另一个click中绑定第二个click。您的代码将每个click上的click绑定到#otherDiv2 #otherDiv1。对于以下过程不需要stopPropagation().

$('#div1').on('click', '#otherDiv1', function(event) {
    //Show popup
    $('#popupDiv').bPopup({
        modalClose: false,
        follow: [false, false],
        closeClass: 'close'
    });
});
$('#div2').on('click', '#otherDiv2', function(event) {
    // here is ajax request         
    // close popup          
    $('#popupDiv').bPopup().close();
});
但是,如果需要在另一个事件中绑定事件

,则首先从#otherDiv2中取消绑定事件,然后再次绑定。

$('#div1').on('click', '#otherDiv1', function(event) {
    //Show popup
    $('#popupDiv').bPopup({
        modalClose: false,
        follow: [false, false],
        closeClass: 'close'
    });
    $('#div2').off('click').on('click', '#otherDiv2', function(event) {
      // here is ajax request         
      // close popup          
      $('#popupDiv').bPopup().close();
   });
});

我想你可以使用

event.stopImmediatePropagation()

以阻止冒泡。

http://api.jquery.com/event.stopImmediatePropagation/

如果你使用相当新版本的jQuery,每个ajax请求都会返回延迟对象,你可以将其存储在点击处理程序的外部范围内并进行分析,以便取消现有请求或不启动新请求。

还有一个叫做节流的概念,还有jquery的插件可以为你做。