Possible Duplicate:
javascript closure not working as it should
查看第一个代码:
var count = 0;
(function addLinks() {
var count = 0; //this count var is increasing
for (var i = 0, link; i < 5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function () {
count++;
alert(count);//here all the paragraph updates the same variable
};
document.body.appendChild(link);
}
})();
当链接被点击时,每个链接元素的计数器变量不断增加。这是一个方面的结果
第二:
var count = 0;
$("p").each(function () {
var $thisParagraph = $(this);
var count = 0; //this count var is increasing too.so what is different between them .They both are declared within the scope in which closure was declared
$thisParagraph.click(function () {
count++;
$thisParagraph.find("span").text('clicks: ' + count);
$thisParagraph.toggleClass("highlight", count % 3 == 0);
});
});
这里的闭包函数没有按方面工作。每次单击段落元素时,计数器变量都会增加,但单击第二个段落元素时不会显示该增量?这是什么原因?为什么会发生这种情况?每个段落元素的计数变量都没有增加。在我之前的问题中,我没有得到满意的答案,所以我请求
最佳答案
counter
变量在 .each
内声明环形。因此,每个<p>
有自己的计数器,因为该函数针对每个 <p>
执行。任何两个段落都不会更新同一个变量。
另一方面,在第一个片段中,只有一个 counter
使用的变量(循环外),通过任何 <p>
的任何点击来更新该变量。 。作为旁注,请注意,在循环内部声明不会产生任何影响 - 您必须为每个 <p>
创建一个闭包 分别每个 <p>
有自己的计数器变量。
关于javascript 闭包的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14646067/