简体   繁体   English

如何防止JavaScript冒泡

[英]How to prevent javascript bubbling

I am talking about Jquery. 我说的是Jquery。 Say, I have a button, I clicked it and a new div is dynamically created. 说,我有一个按钮,单击了它,然后动态创建了一个新的div。 I clicked again and another div is created. 我再次单击并创建另一个div。 This way I created 3 div. 这样我创建了3 div。

Each of the newly created div also dynamically creates a button, clicking which I want to get alert('something') 每个新创建的div也会动态创建一个按钮,单击该按钮我想得到警报(“某物”)

Problem is that, when I click button of 1st div(newly created div) I get the alert 3 times, When I click button of 2nd div(newly created div), I get alert 2 times. 问题是,当我单击第一个div(新创建的div)按钮时,我会收到3次警报;当我单击第二个div(新创建的div)按钮时,我会收到2次警报。 For every one click I want to get alert only once . 对于每一次单击,我希望收到一次警报。 But I am facing Javascript bubbling* 但是我正面临着Javascript起泡*

My Javascript and HTML codes: 我的Javascript和HTML代码:

 $("#btn11").click(function(){ var nw="<div class='product_input'><input type='text'/><br/>"; nw+="<button type='button' class='btn12'>Add category</button>"; nw+="</div>"; $("#apnd1").append(nw); $(".btn12").click(function(){ alert("jhfj"); }); }); 
 <div id="apnd1"></div> <button type="button" id="btn11">Add product</button> 

How to get rid of this? 如何摆脱这个?

Dont bind the events inside another evens. 不要将事件绑定到另一个事件中。 You can bind it outside. 您可以将其绑定到外面。 Since it is dynamically created, you need to use delegate to bind the events. 由于它是动态创建的,因此需要使用委托来绑定事件。 Then you will not get multiple alerts 这样您将不会收到多个警报

$("#btn11").click(function() {
    var nw = "<div class='product_input'><input type='text'/><br/>";
    nw += "<button type='button' class='btn12'>Add category</button>";
    nw += "</div>";
    $("#apnd1").append(nw);
});
$("#apnd1").on("click", ".btn12", function() {
    alert("jhfj");
});

Fiddle 小提琴

Use event delegation for the same, Demo 使用事件委托进行演示

$(document).ready(function(){
        $("#btn11").click(function(){
            var nw="<div class='product_input'><input type='text'/><br/>";
            nw+="<button type='button' class='btn12'>Add category</button>";
            nw+="</div>";
            $("#apnd1").append(nw);            
        });
    $(document).on('click', ".btn12", function(){
                alert("jhfj");
            });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM