javascript关闭不能正常工作 [英] javascript closure not working as it should

查看:52
本文介绍了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);
   }
 })();

点击链接后,每个链接元素的计数器变量都会继续增加。这是预期的结果。

When the link gets clicked the counter variable keeps on increasing for each link element. This is the expected result.

第二:

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变量都没有增加。

Here the closure function is not working as expected. On each click on the paragraph element, the counter var is increased but that increment is not displayed on click on second paragraph element? What is the reason for this? Why is this happening? The count variable is not increasing for each paragraph element.

推荐答案

你的意思是:

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关闭不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆