javascript 闭包无法正常工作

标签 javascript jquery

查看第一个代码:

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

最佳答案

你的意思是:

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 闭包无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14645471/

相关文章:

jquery - ajax 测试是否登录?

javascript - jQuery 无法在设计模式下捕获 keyup 目标元素

javascript - 三个下拉事件更改不起作用

javascript - CORS - 预检请求后发出的请求期望 'Access-Control-Allow-Credentials' 为真

javascript - 如何选择特定类名的所有元素?

javascript - order.before : 的 Brunch.io brunch-config.js 语义

javascript - 如何将 promise 传递给 AngularJS 中的 Controller

javascript - JQuery Popup 仅适用于一个项目

javascript - 合并两个数组中的相关对象

javascript - 无法使用 Angular.js 在数组中有序获取文件