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); }); }); 

这里的闭包function没有按预期工作。 每次点击段落元素时,计数器var都会增加,但点击第二段元素时不显示该增量? 这是什么原因? 为什么会这样? 每个段落元素的count变量不会增加。

你的意思是:

 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); }); });