看到的第一个代码: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);
};
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);
});
});
这里如期关闭功能无法正常工作。每次单击段落元素时,计数器var
都会增加,但在第二段元素上单击时不会显示该增量值?这是什么原因?这是为什么发生?每个段落元素的count变量不会增加。
传递给'。点击()函数'本身是一个封闭,和你做的第一件事情之一是设置局部变量'count'为'0 '在里面; “count”的值永远不会变成别的,因为你明确地告诉它总是0. –