Jquery each() 计数器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3929465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:21:51  来源:igfitidea点击:

Jquery each() Counter

jquery

提问by adamg2000

I've done some searching around the documentation, and spent a while on the net but cannot find a solution to this! I want the alert to tell me which iteration of each() it was on when the .thumb is clicked.

我已经对文档进行了一些搜索,并在网上花了一段时间但找不到解决方案!我希望警报告诉我单击 .thumb 时它处于 each() 的哪个迭代。

EG: There are six .thumb's I click on number 3, the browser pops-up 3!

EG:有六个.thumb,我点击数字3,浏览器弹出3!

What actually happens is regardless of which .thumb is clicked, 6 pops up.

实际发生的是无论点击哪个 .thumb,都会弹出 6。

var counter = 1;
$('.thumb').each(function () {
    $(this).click(function () {
        alert (counter);
    });
    counter++;
});

Any help is gratefully received.

非常感谢任何帮助。

回答by Nick Craver

That's because you're sharing the same countervariable for allclickhandlers and it is whatever it ends up being at the end of the loop. Instead, use the one passed into the loop (the index parameter of the .each()that's already there), like this:

那是因为您counter所有click处理程序共享相同的变量,并且它是循环结束时最终出现的任何变量。相反,使用传递到循环中的.each()那个(已经存在的索引参数),如下所示:

$('.thumb').each(function (i) {
    $(this).click(function () {
        alert (i+1); //index starts with 0, so add 1 if you want 1 first
    });
});

You can test it here.

你可以在这里测试

回答by user113716

To use a solution like @Paulo suggested, you would need to do so like this:

要使用@Paulo 建议的解决方案,您需要这样做:

var list = $('.thumb');

for(var i=0; i<list.length; i++) {
    (function( i_local ) {
        list.eq( i ).click(function(){
            alert(i_local);
        });
    })( i + 1 );
}?

...although I'd use @Nicks .each()solution instead. Much cleaner.

...虽然我会改用@Nicks.each()解决方案。干净多了。