Javascript 臭名昭著的循環問題? [複製] - Javascript infamous Loop issue? [duplicate]

問題:

This question already has answers here : 這個問題在這裏已經有了答案
Closed 7 years ago . 7年前關閉。

I've got the following code snippet.我有以下代碼片段。

function addLinks () {
    for (var i=0, link; i<5; i++) {
        link = document.createElement("a");
        link.innerHTML = "Link " + i;
        link.onclick = function () {
            alert(i);
        };
        document.body.appendChild(link);
    }
}

The above code is for generating 5 links and bind each link with an alert event to show the current link id.上面的代碼用於生成 5 個鏈接,併爲每個鏈接綁定一個警報事件以顯示當前鏈接 id。 But It doesn't work.但它不起作用。 When you click the generated links they all say "link 5".當您單擊生成的鏈接時,它們都會說“鏈接 5”。

But the following codes snippet works as our expectation.但是下面的代碼片段符合我們的預期。

function addLinks () {
    for (var i=0, link; i<5; i++) {
        link = document.createElement("a");
        link.innerHTML = "Link " + i;
        link.onclick = function (num) {
            return function () {
                alert(num);
            };
        }(i);
        document.body.appendChild(link);
    }
}

The above 2 snippets are quoted from here .以上 2 個片段引用自此處 As the author's explanation, seems the closure makes the magic.正如作者的解釋,似乎閉包使人變魔術。

But how it works and How closure makes it work are all beyond my understanding.但是它是如何工作的以及閉包如何使它工作都超出了我的理解。 Why the first one doesn't work while the second one works?爲什麼第一個不起作用而第二個起作用? Can anyone give a detailed explanation about the magic?誰能詳細解釋一下這個魔法?

thanks.謝謝。


解決方案:

參考一: https://stackoom.com/question/65TN
參考二: Javascript infamous Loop issue? [duplicate]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章