gpt4 book ai didi

javascript - 添加点击监听器以在循环中列出项目

转载 作者:行者123 更新时间:2023-11-30 09:57:36 25 4
gpt4 key购买 nike

我有以下代码:

    // Iterate through each of the children
for(j = 0; j < len; j++) {
var entry = sortedArray[j];

// Each entryLI is a child of nameOL <ol> element
var entryLI = document.createElement("li");

// Each entryLI should have a unique click listener
entryLI.addEventListener("click", function(event) {entry.onListItemClick()});

// Set the text of the <li> to the name of the entry
var nameNode = document.createTextNode(entry.entryName);
entryLI.appendChild(nameNode);

// Append the entry list item to the ordered list
nameOL.appendChild(entryLI);
}

我试图在这个循环中为每个列表项提供一个处理点击事件的事件监听器。但是,出于某种原因,单击任何列表项都会调用列表中最后 项的事件监听器。

谁能给我解释一下这是为什么?

我是从完全不同的语言转向 JavaScript 的,我正在为基于原型(prototype)的类而苦苦挣扎。

最佳答案

entry 变量在每个循环中都会被覆盖。一种避免这种情况的方法是:

for(j = 0; j < len; j++) {

(function(entry){

....

})(sortedArray[j])

}

IIF(立即调用函数)为每次迭代分别确定入口变量的范围。

关于javascript - 添加点击监听器以在循环中列出项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33290202/

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