Javascript在foreach循环中添加事件侦听器只有最后一个条目有效
我有一个函数,它通过数组向div添加Javascript在foreach循环中添加事件侦听器只有最后一个条目有效,javascript,asp.net,loops,event-listener,Javascript,Asp.net,Loops,Event Listener,我有一个函数,它通过数组向div添加元素。然后它向当前元素添加一个事件侦听器(一个onclick),但只有通过函数的最后一个元素由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("
元素。然后它向当前
元素添加一个事件侦听器(一个onclick
),但只有通过函数的最后一个元素由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');
};
};
var runstr=[];
//txt来自由“\n”分隔的选项卡文本文件的内容
forEach(函数(lcb){//lcb遍历txt的每一行
lcb=lcb.split(“,30);//按制表符拆分行
//MainContent_Infralist是一个div,其中列出了元素,lcb[2]是标题
document.getElementById(“MainContent\u Infralist”).innerHTML=
document.getElementById(“MainContent\u Infrastruct”).innerHTML+
''+lcb[2]+'';
//我将id放入一个数组中,以便稍后获得标记的索引
runstr.push(“Infralist_”+lcb[2]);
//我在这里使用openlayers,我试图设置
//list.only单击可触发标记上的鼠标向下移动。
//问题是:它有效,但只适用于我列表的最后一个条目。。。
document.getElementById(“Infralist_389;”+lcb[2]).onclick=function(){
var theM=runstr.indexOf(“Infralist_u3;”+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>';
@kamituel你说得对,我正在撤回重复投票。非常感谢!!!它很有效!!!我还不能投票,但当我可以投票时我会做…@user2519977-很高兴我帮了忙:)经验法则是不要使用
innerHTML
进行DOM操作。
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
}