使用Jquery将函数绑定到多个元素

时间:2021-10-27 14:26:30

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

我有这个jquery的小问题:我需要做这样的事情:

$(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...

因此,当您单击div#a时,您将获得“链接a”警报,div#b上的“链接b”等等...问题是如果您运行此代码,则单击每个元素将发出警报(结果,“链接c”)似乎只为每个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?

当然我可以通过编辑函数来使用div的id并使用$(this)来破解它,但是对于cursiosity:有没有办法让这个循环工作?通过为函数中的每个元素创建和分配新函数?

Thx in advance...

先谢谢......

9 个解决方案

#1


Use a closure: (a "this" solution is more elegant, but I'm posting this because a now deleted answer had a closure solution that didn't work)

使用一个闭包:(一个“这个”解决方案更优雅,但我发布这个因为一个现在删除的答案有一个无效的闭包解决方案)

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

    for (var x in links){
        $("#" + x).css("border","1px solid #000");
        $("#" + x).click(
            function(xx){ 
                return function() { alert(xx) };
            }(x)
        );
    };
});

#2


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

关于jQuery的好处是它允许链接和绑定多个元素,就像css一样。

$(document).ready(function(){

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

});

#3


I believe this is what you're after:

我相信这就是你所追求的:

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

    $.each(links, function(id,text){
      $("#"+id)
       .css("border","1px solid #000")
       .click(function(){ alert(text) })
    })
});

#4


Working Demo http://jsfiddle.net/FWcHv/

工作演示http://jsfiddle.net/FWcHv/

in you code you are calling jQuery constructor many times i.e $('#a') than $('#b') and $('#c') instead you should call like $('#a,#b,#c')

在您的代码中,您多次调用jQuery构造函数,即$('#a')而不是$('#b')和$('#c'),而应该调用$('#a,#b,#c “)

In my code i have passed through all the id's using $.each and combined them and in the next step i have used $('#a,#b,#c') stored in variable x to make the code optimized and easy.

在我的代码中,我使用$ .each传递所有id并将它们组合在一起,并在下一步中使用存储在变量x中的$('#a,#b,#c')来使代码优化和简单。

i have also made a check that if links{} is empty it will not process using variable i

我还检查了如果链接{}为空,则不会使用变量i进行处理

$(document).ready(function () {
    links = {};
    links.a = "Link a";
    links.b = "Link b";
    links.c = "Link c";
    i = 0;
    x = '';
    $.each(links, function (id) {
        x += "#" + id + ',';
        i++;
    });
    if (i > 0) {
        $($(x.slice(0, -1))).css("border", "1px solid #000").click(function () {
            alert($(this).text());
        });
    }
});

#5


<script type="text/javascript">
$(document).ready(function(){
    $('.links').css("border","1px solid #000");
    $('.links').live('click', function() {
        alert("Link " + $(this).attr('id'));
    });
});
</script>
</head>
<body>
<div id="a" class="links">a</div><br />
<div id="b" class="links">b</div><br />
<div id="c" class="links">c</div><br />

#6


You need to use "this".

你需要使用“这个”。

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

    for (var x in links){
        $("#" + x).css("border","1px solid #000");
        $("#" + x).click(function(){
                alert("Link "+this.id+" Alert!");
        });
    }
});

#7


<script type="text/javascript">
$(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").click(function(){
                alert($(this).attr('id'));
        });
    }
});
</script>

</head>

<body>

<div id="a">a</div><br />
<div id="b">b</div><br />
<div id="c">c</div><br />

#8


Seeing as you are hardcoding the elements to be effected anyways, you might as well do it this way as it's likely faster and it's cleaner, IMO:

看到你正在硬编码要被影响的元素,你不妨这样做,因为它可能更快,更清洁,IMO:

$("#a,#b,#c").css("border","1px solid #000");
$("#a,#b,#c").click(function(){
    alert("Link "+this.id+" Alert!");
});

Edit: I didn't see the last part of your question... Sorry. You can also do this:

编辑:我没有看到你问题的最后一部分...抱歉。你也可以这样做:

var links = {};
links.a = "Link a";
links.b = "Link b";
links.c = "Link c";

var ids = '';
$.each(function(key,val) {
    ids += "#"+key+","; // extra commas are ignored in jQuery
});

$(ids)
    .css("border","1px solid #000")
    .bind('click',function(){
        alert("Link "+this.id+" Alert!");
    });

#9


Try using:

$(window).load(function(){

}); 

:)

#1


Use a closure: (a "this" solution is more elegant, but I'm posting this because a now deleted answer had a closure solution that didn't work)

使用一个闭包:(一个“这个”解决方案更优雅,但我发布这个因为一个现在删除的答案有一个无效的闭包解决方案)

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

    for (var x in links){
        $("#" + x).css("border","1px solid #000");
        $("#" + x).click(
            function(xx){ 
                return function() { alert(xx) };
            }(x)
        );
    };
});

#2


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

关于jQuery的好处是它允许链接和绑定多个元素,就像css一样。

$(document).ready(function(){

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

});

#3


I believe this is what you're after:

我相信这就是你所追求的:

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

    $.each(links, function(id,text){
      $("#"+id)
       .css("border","1px solid #000")
       .click(function(){ alert(text) })
    })
});

#4


Working Demo http://jsfiddle.net/FWcHv/

工作演示http://jsfiddle.net/FWcHv/

in you code you are calling jQuery constructor many times i.e $('#a') than $('#b') and $('#c') instead you should call like $('#a,#b,#c')

在您的代码中,您多次调用jQuery构造函数,即$('#a')而不是$('#b')和$('#c'),而应该调用$('#a,#b,#c “)

In my code i have passed through all the id's using $.each and combined them and in the next step i have used $('#a,#b,#c') stored in variable x to make the code optimized and easy.

在我的代码中,我使用$ .each传递所有id并将它们组合在一起,并在下一步中使用存储在变量x中的$('#a,#b,#c')来使代码优化和简单。

i have also made a check that if links{} is empty it will not process using variable i

我还检查了如果链接{}为空,则不会使用变量i进行处理

$(document).ready(function () {
    links = {};
    links.a = "Link a";
    links.b = "Link b";
    links.c = "Link c";
    i = 0;
    x = '';
    $.each(links, function (id) {
        x += "#" + id + ',';
        i++;
    });
    if (i > 0) {
        $($(x.slice(0, -1))).css("border", "1px solid #000").click(function () {
            alert($(this).text());
        });
    }
});

#5


<script type="text/javascript">
$(document).ready(function(){
    $('.links').css("border","1px solid #000");
    $('.links').live('click', function() {
        alert("Link " + $(this).attr('id'));
    });
});
</script>
</head>
<body>
<div id="a" class="links">a</div><br />
<div id="b" class="links">b</div><br />
<div id="c" class="links">c</div><br />

#6


You need to use "this".

你需要使用“这个”。

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

    for (var x in links){
        $("#" + x).css("border","1px solid #000");
        $("#" + x).click(function(){
                alert("Link "+this.id+" Alert!");
        });
    }
});

#7


<script type="text/javascript">
$(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").click(function(){
                alert($(this).attr('id'));
        });
    }
});
</script>

</head>

<body>

<div id="a">a</div><br />
<div id="b">b</div><br />
<div id="c">c</div><br />

#8


Seeing as you are hardcoding the elements to be effected anyways, you might as well do it this way as it's likely faster and it's cleaner, IMO:

看到你正在硬编码要被影响的元素,你不妨这样做,因为它可能更快,更清洁,IMO:

$("#a,#b,#c").css("border","1px solid #000");
$("#a,#b,#c").click(function(){
    alert("Link "+this.id+" Alert!");
});

Edit: I didn't see the last part of your question... Sorry. You can also do this:

编辑:我没有看到你问题的最后一部分...抱歉。你也可以这样做:

var links = {};
links.a = "Link a";
links.b = "Link b";
links.c = "Link c";

var ids = '';
$.each(function(key,val) {
    ids += "#"+key+","; // extra commas are ignored in jQuery
});

$(ids)
    .css("border","1px solid #000")
    .bind('click',function(){
        alert("Link "+this.id+" Alert!");
    });

#9


Try using:

$(window).load(function(){

}); 

:)