重複の可能性:
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);//here all the paragraph updates the same variable
};
document.body.appendChild(link);
}
})();
リンクがクリックされると、カウンター変数はリンク要素ごとに増加し続けます。これはアスペクト化された結果です
2番:
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 が増加しますが、2 番目の段落要素をクリックしてもその増分は表示されませんか?これの背後にある理由は何ですか?なぜこれが起こっているのですか?カウント段落要素ごとに変数が増加していません。前の質問で満足のいく答えが得られなかったので、要求しました