我想动态创建一个按钮,该按钮将从对象中删除一个键。然而,此时我只是使用警报来测试正确的值,该值稍后将传递给将删除密钥的函数。我正在运行一个 for-in 循环,并试图将迭代器传递给循环中调用的函数。问题是警报语句正在使用迭代器“i”,并且随着循环结束,此警报的所有实例都已更改为“i”的最终值。(我希望这是有道理的!)
locations = {};
function Location(nickname, address) {
this.nickname = nickname;
this.address = address;
}
Location.prototype.showLocations = function() {
var x=document.getElementById("demo");
output = "<table><tr><th>Location</th><th>Address</th><th>Delete</th></tr>";
for (i in locations) (function(i)
{
output+=listThis(i);
}) (i);
// for (i in locations) {
// output+=listThis(i);
// }
output+="</table>"
x.innerHTML=output;
}
function listThis(i){
thisLoc = locations[i].nickname;
var thisOutput="<tr><td>"+locations[thisLoc].nickname+"</td><td>"+locations[thisLoc].address+"</td><td><input type='button' value='X' onclick='alert(locations[thisLoc].nickname)' /></td></tr>";
return thisOutput;
}
function enterLocation() {
var address = document.getElementById('address').value;
var nickname = document.getElementById('nickname').value;
locations[nickname] = new Location(nickname, address);
locations[nickname].showLocations();
}
标记是:
<p id="demo">Table to go in here.</p>
<div id="panel">
<input id="nickname" type="textbox" placeholder="Location Name" />
<input id="address" type="textbox" placeholder="Sydney, NSW" />
<input type="button" value="Enter" onclick="enterLocation()" />
</div>
请注意,我已尝试使用在这篇文章Javascript 中找到的信息 - 如何在带有回调的 for 循环中使用迭代器,但没有成功。你会看到我最初尝试的另一个 for 循环被注释掉了。