0
 for(var m=1;m<=26;m++)
{

$("#letter"+m).click(function() {
    $("#letter1").attr('value', m); 
    j = 0;

    setValue(this.value, length);
    changeImage("#img");
})
}

在上面的代码中,一切都按预期进行,但唯一的问题是:当我单击 letter1、letter2 等时,letter1 上的值应分别为 1,2 等,如我所料

$("#letter1").attr('value', m);

但是单击任何按钮时该值始终为 27,为什么?

4

3 回答 3

3

Igor's right about the reason (by the time the handler executes, m has long been 27), but I'd suggest a different solution.

If we use a different variable that does not change with the loop, you will get the expected behavior. The easiest way to do this as JavaScript has function scope is to use a function:

function attachHandler(m) {
    // Since it's an argument, the m in here will initially take the value of the
    // m outside, but it's not the same variable, so it won't change as the
    // outside m changes.
    $("#letter"+m).click(function() {
        $("#letter1").attr('value', m); 
        j = 0;
        setValue(this.value, length);
        changeImage("#img");
    });
}
for(var m=1;m<=26;m++) {
    attachHandler(m);
}

A common idiom for this is to use an immediately-invoked function expression:

for(var m = 1; m <= 26; m++) {
    (function(m) {
        $("#letter"+m).click(function() {
            $("#letter1").attr('value', m); 
            j = 0;
            setValue(this.value, length);
            changeImage("#img");
        });
    })(m);
}
于 2013-05-29T04:45:57.280 回答
0

您的循环每次运行 26 次,每次递增 m,因此 m 最终为 27。也许您想要的是将不同的 var 设置为 1 并使用它

于 2013-05-29T04:37:43.143 回答
0

click处理程序执行时,循环早已结束m并被赋值为 27 - 循环终止。

for(var m=1;m<=26;m++)
{
  $("#letter"+m).attr("valueOfM", m);
  $("#letter"+m).click(function() {
    $("#letter1").attr('value', $(this).attr("valueOfM")); 
    j = 0;

    setValue(this.value, length);
    changeImage("#img");
  });
}
于 2013-05-29T04:37:05.657 回答