更新时间: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.