I'm having several div's #mydiv1, #mydiv2, #mydiv3, ... and want to assign click handlers to them:

$(document).ready(function(){
  for(var i = 0; i < 20; i++) {
    $('#question' + i).click( function(){
      alert('you clicked ' + i);
    });
  }
});

But instead of showing 'you clicked 3' when click on #mydiv3 (as for every other click) I get 'you clicked 20'. What am I doing wrong?

推荐答案

在Javascript中创建closures in loops是一个常见的错误.你需要有这样的回调函数:

function createCallback( i ){
  return function(){
    alert('you clicked' + i);
  }
}

$(document).ready(function(){
  for(var i = 0; i < 20; i++) {
    $('#question' + i).click( createCallback( i ) );
  }
});

Update June 3, 2016: since this question is still getting some traction and ES6 is getting popular as well, I would suggest a modern solution. If you write ES6, you can use the let keyword, which makes the i variable local to the loop instead of global:

for(let i = 0; i < 20; i++) {
  $('#question' + i).click( function(){
    alert('you clicked ' + i);
  });
}

It's shorter and easier to understand.

Jquery相关问答推荐

提交表单时运行自定义验证脚本

使用jQuery筛选器搜索输入仅适用于单词的一部分

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

如果选中了三个sibling ,则选中一个复选框

JQuery:$.get 不是函数

禁用提交按钮,直到所有字段都有值

在 JSON 对象上使用 jQuery 的 find()

如何使用 jQuery Select 所有复选框?

TypeScript 中是否有this的别名?

如何在 jQuery 中存储全局值(不一定是全局变量)?

试图检测浏览器关闭事件

数字键盘的keyCode值?

判断元素是否为 div

Jquery Ajax 错误处理忽略中止

jQuery:如果页面底部有外部 JS,为什么要使用 document.ready?

如何从 jQuery UI datepicker 获取日期

带有 jQ​​uery 的饼图

用作 Google Chrome 书签

父母的jQuery父母

如何使用 jQuery 取消设置元素的 CSS 属性?