2

看第一个代码:

 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都会增加,但单击第二个段落元素时不会显示该增量?这是什么原因?为什么会这样?每个段落元素的计数变量没有增加。

4

1 回答 1

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);
  });
});
于 2013-02-01T11:43:25.463 回答