I have 50 dynamically generated HTML buttons as follows:
Try
$(".btn").click(function() {
// Do something
});
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:
$(".btn").click(function() {
// Do something
});
If behaviour for each button is different, assign events to different #IDs
$("#btn1").click(function {
// Do something
});
2. Use .on():
jQuery 1.7 introduced .on() method that wraps all listeners to 1 method.
$("button").on("click", function() {
// Do something
});
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.
$("#wrapper").on("click", "button", function() {
// Do something
});
Useful resources: