可能重复:
javascript 闭包不能正常工作
看第一个代码:
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);
});
});
这里的闭包函数没有按方面工作。每次单击段落元素时,计数器变量都会增加,但单击第二个段落元素时不会显示该增量?这是什么原因?为什么会发生这种情况?计数每个段落元素的变量都没有增加。在我之前的问题中,我没有得到满意的答案,所以我要求