JavaScript closures and variable scope

前端 未结 2 1638
小蘑菇
小蘑菇 2020-12-21 04:12

I am having trouble with JS closures:

// arg: an array of strings. each string is a mentioned user.
// fills in the list of mentioned users. Click on a menti         


        
2条回答
  •  不思量自难忘°
    2020-12-21 04:52

    Your iterator i is stored as a reference, not as a value and so, as it is changed outside the closure, all the references to it are changing.

    try this

    function fillInMentioned(mentions) { 
        var mentionList = document.getElementById("mention-list"); 
        mentionList.innerHTML = ""; 
        for (var i = 0; i < mentions.length; i++) { 
            var newAnchor = document.createElement("a"); 
    
            // Set the index as a property of the object 
            newAnchor.idx = i;
            newAnchor.onclick = function () { 
                // Now use the property of the current object
                loadUsernameInfo(mentions[this.idx]) 
            }; 
    
            // give this anchor the necessary content 
            newAnchor.innerHTML = mentions[i]; 
    
            var newListItem = document.createElement("li"); 
            newListItem.appendChild(newAnchor); 
            mentionList.appendChild(newListItem); 
        } 
        document.getElementById("mentions").setAttribute("class", "");  
    } 
    

提交回复
热议问题