gpt4 book ai didi

Javascript 使用 for-in 循环迭代器设置变量

转载 作者:行者123 更新时间:2023-11-30 17:48:04 28 4
gpt4 key购买 nike

我想动态创建一个按钮,该按钮将从一个对象中删除一个键。然而,此时我只是使用警报来测试正确的值,该值稍后将传递给将删除 key 的函数。我正在运行一个 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 - how to work with the iterator in a for loop with callbacks 中找到的信息但没有成功。您会看到我最初尝试的另一个 for 循环被注释掉了。

最佳答案

问题出在在线 onclick 处理程序中。

您编写 onclick='alert(locations[thisLoc].nickname)' 并且此处 thisLoc 不是对您的变量的直接引用。它是一些在运行时评估的名称。

thisLoc = locations[i].nickname; 行中,您定义了global 变量 thisLoc,每次迭代都会覆盖该值。稍后当 onclick 被处理时,这个具有(总是)最新值的全局变量被访问。

有几种解决方案:

  • 不要像 minitech 所说的那样使用 HTML 构建——使用 DOM 操作
  • 在构建时将值写入某些 DOM 属性并在 onclick 处理程序中读取它:

    "<input type='button' value='X' data-location-name="' + thisLoc + '" onclick='alert(locations[this.getAttribute('data-location-name')].nickname)' />"

关于Javascript 使用 for-in 循环迭代器设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19696829/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com