Wednesday, January 6, 2010

Specify multiple selectors with jQuery

Bad Example

For example, to assign the same click handler to the elements #foo, #bar and #baz you could do this:


$('#foo').click(function() {
common_function();
});
$('#bar').click(function() {
common_function();
});
$('#baz').click(function() {
common_function();
});
function common_function() {
// do something here
}

This is far from ideal because it is rather verbose, but at least the common stuff that's done is done in a common function so if it needs to be changed it can be changed in one place.

Good Example

A far better way to do it is like this, where each selected element is separated by a comma:


$('#foo, #bar, #baz').click(function() {
// do something here
});

This is much more concise and compact way of achieving the same thing and means a separate common function does not need to be called.

No comments:

Post a Comment