JavaScript闭包无法正常工作

javascript closure not working as it should

本文关键字:工作 常工作 闭包 JavaScript      更新时间:2023-09-26

参见第一个代码:

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