Jquery each()Counter

我已经做了一些搜索文档,并在网上花了一段时间,但找不到解决方案!我想要的警报告诉我在每次()它是在.thumb单击时的迭代。

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

实际发生的是不管哪个.thumb被点击,6弹出。

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

任何帮助,谢谢。

解决方法

这是因为你为所有的点击处理程序共享相同的计数器变量,它是最终在循环结束时的任何。相反,使用传递到循环中的一个(已经存在的 .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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...