Search code examples
javascriptfunctionloopscycle

how to apply multiple selectors?


How can i write this javascript code in a loop ? I am using

$("#b1").click(function ( event ) {
event.preventDefault();
$("#a1").hide();
});
$("#b2").click(function ( event ) {
event.preventDefault();
$("#a2").hide();
});
$("#b3").click(function ( event ) {
event.preventDefault();
$("#a3").hide();
});
...etc

Solution

  • if your id always ends with number, you could do like:

    $("a").filter(function() {
        return $(this).attr("id").match(/\d+$/);
    }).click(function(evt) {
        evt.preventDefault();
        $(this).hide();
    });