gpt4 book ai didi

Javascript在foreach循环中添加事件监听器只有最后一个条目有效

转载 作者:行者123 更新时间:2023-11-28 11:58:42 28 4
gpt4 key购买 nike

我有一个函数,它遍历一个数组并添加 <h3>元素到 div。然后它将事件监听器( onclick )添加到当前 <h3> 。元素,但只有通过该函数的最后一个元素由 onclick 设置.

var runstr = [];

//txt comes from the content of a tab separated textfile spilt by '\n'
txt.forEach(function (lcb) { //lcb goes through each line of txt
lcb = lcb.split(" ", 30); //split the line by tab
//MainContent_Infralist is a div where the <h3> elements are listed and lcb[2] is the title
document.getElementById("MainContent_Infralist").innerHTML =
document.getElementById("MainContent_Infralist").innerHTML +
'<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';
//I put the id into an array to get the index of the marker later
runstr.push("Infralist_" + lcb[2]);

//I'm working with openlayers here i try to set the entry of
//the list.onlick to trigger a mousedown on a marker.
//And there is the problem: It works, but only for the last entry of my <h3> list...
document.getElementById("Infralist_" + lcb[2]).onclick = function () {
var theM = runstr.indexOf("Infralist_" + lcb[2]);
markers.markers[theM].events.triggerEvent('mousedown');
};
};

最佳答案

问题出在这里:

document.getElementById("MainContent_Infralist").innerHTML = 
document.getElementById("MainContent_Infralist").innerHTML +
'<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';

每次分配给 innerHTML 时,您基本上都会删除所有内容并重新添加。这会导致所有事件监听器中断。

这就是为什么只有最后一个有效的原因 - 它是分配后唯一一个不再有 innerHTML 操作的原因。

要解决此问题,请使用 document.createElement() 创建元素并使用 element.appendChild() 附加它们。

它可能看起来像:

var header = document.createElement('h3');
header.id = 'Infralist_' + lcb[2];
header.className = 'Infraa';
header.textContent = lcb[2];

document.getElementById('MainContent_Infralist').appendChild(header);

header.onclick = function () {
// you function here
}

关于Javascript在foreach循环中添加事件监听器只有最后一个条目有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18727994/

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