<body>
<div id="links">
</div>
</body>
<script type="text/javascript">
var A = function(j) {
this.b = j;
};
var links = $("#links");
for (var i = 0; i < 100; i++) {
var a = new A(i); // a is the local variable mentioned in the question
links.append($("<a> " + i + " </a>").click(function() {
console.log(a.b);
// when the <a>i</a> is clicked 99 is always printed to console
}));
}
</script>
在上面的脚本中,当点击 <a>45</a>
时,我认为会打印 45 ,而是 99 打印出来。无论点击什么链接,始终会打印 99 。我认为在 console.log()
中访问的 将指向在该特定循环中创建的本地 a ,因此会打印 i 的对应值。为什么会这样?我做错了吗?
无论如何,现在我需要它,以便在单击链接时,对其对应的对象起作用,而不是最后创建的对象。我将如何实现这一目标?
答案 0 :(得分:0)
<强> Demo 强>
尝试
var A = function (j) {
this.b = j;
};
var links = $("#links");
for (var i = 0; i < 100; i++) {
(function () {
var a = new A(i); // a is the local variable mentioned in the question
links.append($("<a> " + i + " </a>").click(function () {
console.log(a.b);
}));
})(i);
}