in Javascript .. If I have a dynamically generated buttons and I want a generic onClick function. How can I do that ?
<script>
for(i=0;i<something.length;i++){
$('body').append('<button id="btnInit'+i+'" >'+i+'</button>');
}
</script>
I don’t want to create a unique onClick function for each button. How can I do a single one that applies to all. e.g display its label text when pressed.
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
clickhandler to thebodyelement and all clicks on those buttons will trigger an event handler. The nicest way to do this in jQuery is to use theonmethod: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
livemethod, butliveusesonbehind the scenes and is far less efficient and flexible.