查看第一个代码:
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变量都没有增加。
答案 0 :(得分:2)
var count = 0;
$("p").each(function() {
var $thisParagraph = $(this);
//var count = 0; //removed this count, as it re-inits count to 0
$thisParagraph.click(function() {
count++;
$thisParagraph.find("span").text('clicks: ' + count);
$thisParagraph.toggleClass("highlight", count % 3 == 0);
});
});