gpt4 book ai didi

Javascript onclick动态for循环获取索引

转载 作者:行者123 更新时间:2023-12-03 02:11:36 25 4
gpt4 key购买 nike

您好,我在以下代码中获取索引时遇到问题:

Contacts.push("test1 test 4232352");
Contacts.push("test2 test2 5435345");
for(var i = 0; i < Contacts.length; i++){

var res = Contacts[i].split(" ");
var font = document.createElement("FONT");
font.innerHTML = res[0] + " " + res[1];
font.style.marginLeft = "10px";
font.onclick = () => { console.log(i); };
document.getElementById("contacts_collection").appendChild(font);
}

在我看来,它应该打印我点击的元素的索引,但无论我点击这两个元素中的哪一个,它总是打印“2”。

最佳答案

问题是使用语句var声明i

另一种方法是使用语句 let 声明 i:

for(let i = 0; i < Contacts.length; i++){}
^^^

或者,您可以使用IIFE保持i的当前值:

var Contacts = ["test1 test 4232352", "test2 test2 5435345"];
for (var i = 0; i < Contacts.length; i++) {
var res = Contacts[i].split(" ");
var font = document.createElement("FONT");
font.innerHTML = "<b>" + res[0] + " " + res[1] + "</b>";
font.style.marginLeft = "10px";

font.onclick = ((index) => () => {
console.log(index);
})(i);

document.body.appendChild(font);
}

关于Javascript onclick动态for循环获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540323/

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