简体   繁体   English

单击动态创建的按钮jQuery

[英]Clicking dynamically created buttons jQuery

I have a jQuery datatable where each row has an add to cart button. 我有一个jQuery数据表,其中每一行都有一个添加到购物车按钮。 If I perform a search or I click on another entry of pages in the table, the table will dynamically load new rows & buttons. 如果执行搜索或单击表中的其他页面条目,该表将动态加载新的行和按钮。 Therefore, I have two types of add to cart buttons - one for the dynamically created buttons and one for the original buttons: 因此,我有两种添加到购物车按钮的类型-一种是动态创建的按钮,另一种是原始按钮:

Click event for dynamically created buttons: 动态创建的按钮的Click事件:

$(document).on('click', 'button.btn.btn-primary.addtocart', function() {
    //add to cart
});

Click event for original buttons: 原始按钮的Click事件:

$(".addtocart").click(function() {
    //add to cart
});

The problem I'm having is if I click the original buttons, the click event fires twice. 我遇到的问题是,如果单击原始按钮,则click事件将触发两次。 Does anyone know of a strategy or work around for this? 有谁知道策略或为此解决?

Use event.stopImmediatePropagation() in the button click handler to stop event from bubbling. 在按钮单击处理程序中使用event.stopImmediatePropagation()可阻止事件冒泡。

$(".addtocart").click(function (event) {
    //                          ^^^^^    Pass event object to the callback
    //add to cart

    event.stopImmediatePropagation();
});

EDIT: 编辑:

If both the handlers are same, I'll suggest to use only a delegated handler for both dynamic and static elements. 如果两个处理程序都相同,我建议对动态和静态元素仅使用委托的处理程序。

$(document).on('click', 'button.btn.btn-primary.addtocart', function () {
    // add to cart
});

It is a easy solution. 这是一个简单的解决方案。

Just use on method in jQuery. 只需在jQuery中使用on方法即可。

$(document).ready(function(){
    $("dynamically_created_element_selector").on("click", function()
    {
        //do whatever u want
    });
});

Demo is here- 演示在这里-

 $(function(){ $('button').on('click',function(){ var r= $('<br/><button class="dynamic_button" type="button">Dynamic Button</button>'); $("body").append(r); }); $(document).on('click', 'button.dynamic_button', function () { alert("Dynamic Element Clicked !!"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <body> <button>Insert after</button> </body> 

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

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