I create elements on the DOM by JS. The question is, how to assign .change() function for each new created element ?
Even nicer than .live()
, from a performance point of view, is .delegate()
. This works in the same way as .live()
: it uses something called event bubbling, which means that when an event is triggered on a DOM element, that element's parents are all notified of the event. delegate
, however, has somewhat nicer syntax and a substantial performance benefit.
$('#parentElement').delegate('select.yourSelectClass', 'change', function() {
// do your processing here
});
#parentElement
can be any selector that matches the common ancestor element of all the select
elements that you are going to add. This might be document.body
, but there will probably be another element in the DOM tree that you can bind to.
select.yourSelectClass
means that the this handler will only be triggered on select elements with the class yourSelectClass
. You could change this selector to use any other jQuery selector syntax as you like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With