I have 50 dynamically generated HTML buttons as follows:
<input type="button" id="btn1" name="myButton" value="Click Me" />
<input type="button" id="btn2" name="myButton" value="Click Me" />
:
:
:
<input type="button" id="btn50" name="myButton" value="Click Me" />
Which is the best way to assign click event to all buttons using jQuery?
By using id
or by using name
attribute ?
This would be an easy way to wrap it all up into one 'on' event and do something based on the button id;
here's a fiddle http://jsfiddle.net/gisheri/CW474/1/
Event listeners cost memory. You have to think carefully about how you should implement the listeners.
1. The straightforward way:
Do not use this
If the behaviour for each button is the same, use a class:
If behaviour for each button is different, assign events to different #IDs
2. Use .on():
jQuery 1.7 introduced .on() method that wraps all listeners to 1 method.
However, we are still binding many listeners on the page.
3. Use a wrapper (use this!):
Wrap your buttons with a div and create one listener for it.
Useful resources: