且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将onClick事件添加到动态生成的按钮?

更新时间:2023-09-29 18:17:16

You can do this by using a Javascript feature called "event bubbling". Ancestor elements are notified of events on their descendent elements.

In this case, you can attach a click handler to the body element and all clicks on those buttons will trigger an event handler. The nicest way to do this in jQuery is to use the on method:

$(document.body).on('click', 'button', function() {
    alert ('button ' + this.id + ' clicked');
});

This will work no matter when the elements are created – before or after the elements were created.

This does exactly the same thing as the live method, but live uses on behind the scenes and is far less efficient and flexible.