简体   繁体   中英

click event on ajax loaded content and dynamic id

I have load content using ajax. need to call on ajax loaded content. i have also try some code but no luck with this.

jQuery(document).ready(function(){
        var itemId = '<?php echo $_item->getId(); ?>';

         jQuery("#cart-sidebar").on("click", '.increment_qty_'+itemId, function(event) {
            console.log("work");
        });

        jQuery("#cart-sidebar").on("click", '.increment_qty_<?php echo $_item->getId(); ?>', function(event) {
            console.log("work");
        });
});

Try to bind the events to document, this ensures that whenever the element is found in DOM it can be fired

jQuery(document).ready(function(){
        var itemId = '<?php echo $_item->getId(); ?>';

          jQuery(document).on("#cart-sidebar","click", '.increment_qty_'+itemId, function(event) {
            console.log("work");
        });

        jQuery(document).on("#cart-sidebar","click", '.increment_qty_<?php echo $_item->getId(); ?>', function(event) {
            console.log("work");
        });
});

There are 2 ways to attach event handlers to content loaded by Ajax.

  1. Attach the event on the done callback of the ajax request. (ref: jQuery Ajax )

     $.ajax({ url: "xyz.php", }) .done(function( content ) { $("#cart-sidebar").on("click", '.increment_qty_'+itemId, function(event) { console.log("work"); }); }); 
  2. Use Event Delegate . This will allow you to attach event listeners to elements even in the future .

Just do like:

jQuery(document).ready(function(){
        var itemId = '<?php echo $_item->getId(); ?>';

         jQuery(document).on("click", '.increment_qty_'+itemId, function(event) {
            console.log("work");
        });


});

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