JavaScript闭包无法正常工作
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);
};
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 变量不会增加。
你的意思是:
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);
});
});
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 正在尝试使用if和else添加类,但无法正常工作
- Jquery FadeIn FadeOut 只工作一次
- Foreach无法在Typescript中工作
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- JS可以在Chrome中工作,但不能在Firefox中工作
- 最大高度转换不;不工作,工作缓慢
- Gulp-rev:不是第一次工作,而是在第一次工作之后工作
- JQuery - Ajax: encodeUriComponent不工作(EncodeUri工作)