Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding function to multiple elements with Jquery

I have this small problem with jquery: I need to do something like this:

$(document).ready(function(){
    links = {};
    links.a = "Link a";
    links.b = "Link b";
    links.c = "Link c";

    for (x in links){
        $("#" + x).css("border","1px solid #000");
        $("#" + x).click(function(){
            alert(x);
        });
    }
});
</script>
<div id="a">a</div><br />
<div id="b">b</div><br />
<div id="c">c</div><br />

So that when you click on div#a you will get "Link a" alert, "Link b" on div#b and so on... The problem is that if you run this code, clicking on each element will give alert("Link c") as result, it seems that only the last function variation is assigned to each div...

Of course i can hack it by editing the function to work with div's id and using $(this), but for cursiosity: is there a way to make this cycle work? By creating and assigning a new function to each element in function?

Thx in advance...

like image 258
Alekc Avatar asked May 15 '09 14:05

Alekc


1 Answers

the nice thing about jQuery is it allows chaining and binding multiple elements just like css.

$(document).ready(function(){

    $('#a,#b,#c')
        .css("border","1px solid #000")
        .bind('click',function(){
            // do something
         });

});
like image 167
Big J Avatar answered Nov 07 '22 07:11

Big J