2013-02-01 86 views
2

看到的第一个代码: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); 
    } 
})(); 

当链接被点击的计数器变量不断为每个链接元素增加。这是预期的结果。

二:

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变量不会增加。

+0

传递给'。点击()函数'本身是一个封闭,和你做的第一件事情之一是设置局部变量'count'为'0 '在里面; “count”的值永远不会变成别的,因为你明确地告诉它总是0. –

回答

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

谢谢你的信息。 –

+0

但是在上面的代码中函数中声明了count变量(第一和第二代码) –

+0

@MaizerePathak:第一个代码示例,同时声明count变量两次,并将它声明为**在循环外**第二个例子已经在循环中嵌入了**。因此在第一个示例中,每次迭代都不会覆盖计数。不像第二个例子中count在每次迭代中被覆盖。 – Nope

相关问题