【发布时间】:2011-01-19 19:51:40
【问题描述】:
我遇到了 JS 闭包问题:
// arg: an array of strings. each string is a mentioned user.
// fills in the list of mentioned users. Click on a mentioned user's name causes the page to load that user's info.
function fillInMentioned(mentions) {
var mentionList = document.getElementById("mention-list");
mentionList.innerHTML = "";
for (var i = 0; i < mentions.length; i++) {
var newAnchor = document.createElement("a");
// cause the page to load info for this screen name
newAnchor.onclick = function () { loadUsernameInfo(mentions[i]) };
// 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", ""); // unhide. hacky hack hack.
}
不幸的是,单击这些锚标记之一会导致这样的调用:
loadUserNameInfo(undefined);
这是为什么?我的目标是这样的锚:
<a onclick="loadUserNameInfo(someguy)">someguy</a>
我怎样才能制作这个?
更新这可行:
newAnchor.onclick = function () { loadUsernameInfo(this.innerHTML) };
newAnchor.innerHTML = mentions[i];
【问题讨论】:
-
这是关于关闭的最常见和重复的问题之一,可能是骗子:stackoverflow.com/questions/1734749stackoverflow.com/questions/643542stackoverflow.com/questions/1582634stackoverflow.com/questions/1331769stackoverflow.com/questions/1331769stackoverflow.com/questions/1552941stackoverflow.com/questions/750486stackoverflow.com/questions/933343stackoverflow.com/questions/1579978@ 987654329@
标签: javascript dom events closures