简体   繁体   中英

Click event not firing with dynamically create buttons

I have dynamically created the buttons in a div. And binding the click and other events for the buttons. But the problem is, click event fired only one for first clicked button. It happens same for the other binding events. The sample code is

 $('#divButtons input[type=button]').each(function () {
     $(this).bind('mouseover', function (e) {
         // some work
     }).bind('mouseout', function (e) {
         // some work
     }).bind('click', function (e) {
         // some work
     });
 });

It works good when bind it on document.ready() But in my case buttons created far after DOM ready.

I also want to know why it behaves like this...?

If using jQuery 1.7+ go for on(), and there's really no need for each() :

$(document).on({
    mouseover: function(e) {
            // some work
    },
    mouseout: function(e) {
           // some work
    },
    click: function(e) {
           // some work
    }
}, '#divButtons input[type=button]');

replace document with nearest non dynamic element for delegated event handler.

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