I have some HTML code that is created dynamically and includes potentially dozens of anchors. I want to add a click handler to each anchor and I can think of a number of different ways but don’t know which one to choose. Assuming the anchors have a class of “myclass” and the code executed when clicked is the same for each.
Method 1
$(document).delegate(".myclass", "click", function() {
// Do some work
});
Method 2:
var $a = $("<a href='#' class='myclass'>Text</a>");
$a.bind("click", function() {
// Do some work
});
Method 3:
function clickHandler() {
// Do some work
}
var $a = $("<a href='#' class='myclass'>Text</a>");
$a.bind("click", function() {
clickHandler();
});
I like Method 2 as the handler code is right where the anchor is created and added to the DOM but if I have lots of these anchors then will JavaScript effectively create dozens of separate functions or is it clever enough to use just one?
If there is some container which contains all of these anchors and you’re using jQuery 1.7 or above then the best solution is the
onAPINote: Make sure to choose the container which is closest to the location where the anchors live. This increases the efficiency of the search to find them on the event fire.