I have the following code which processes a click from a tab and loads contents via ajax:
$(document).ready(function()
{
$("#tab1").click(function()
{
loadTab($(this).attr("href") + "?ajax=1");
return false; // cancel the event
});
$("#tab2").click(function()
{
loadTab($(this).attr("href") + "?ajax=1");
return false; // cancel the event
});
$("#tab3").click(function()
{
loadTab($(this).attr("href") + "?ajax=1");
return false; // cancel the event
});
$("#tab4").click(function()
{
loadTab($(this).attr("href") + "?ajax=1");
return false; // cancel the event
});
});
You’ll notice that there are lots of repeated code.
Is there any way of grouping the #tab1, #tab2, …. into a single .click(function() ?
edit to add some value to the answer (see also other answers, which already mention some, maybe even all, of the following):
you should give the tabs a common identifier, such as a css class: abstraction is good, mmkay?
the tabs are likely to have a common ancestor not too far above. like, they’re all (inside) <li>’s within a single <ul>. explore that and use event delegation.
use the
delegateAPI added in 1.4.2 to spare the guard clause:no need to get overzealous with jquery application: