简体   繁体   中英

Clicking dynamically created buttons jQuery

I have a jQuery datatable where each row has an add to cart button. 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:

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

Click event for original buttons:

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

The problem I'm having is if I click the original buttons, the click event fires twice. Does anyone know of a strategy or work around for this?

Use event.stopImmediatePropagation() in the button click handler to stop event from bubbling.

$(".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.

$(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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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