I need help with a function that iterates through an Array and adds <h3>
elements to a div. The function then attaches an event listener (an onclick
) to the current <h3>
element, but for some reason, only the last element processed by the function is triggering the onclick
event.
var runstr = [];
//txt is derived from content in a tab-separated text file split by '\n'
txt.forEach(function (lcb) { //lcb iterates over each line of txt
lcb = lcb.split(" ", 30); //split the line by tab
//MainContent_Infralist is the div where the <h3> elements are listed and lcb[2] represents the title
document.getElementById("MainContent_Infralist").innerHTML =
document.getElementById("MainContent_Infralist").innerHTML +
'<h3 class="Infraa" id="' + "Infralist_" + lcb[2] + '">' + lcb[2] + '</h3>';
//I store the id in an array to retrieve the marker index later
runstr.push("Infralist_" + lcb[2]);
//I'm using openlayers here to trigger a mousedown on a marker when a list entry is clicked.
//The issue arises where it only works for the last entry in my <h3> list...
document.getElementById("Infralist_" + lcb[2]).onclick = function () {
var theM = runstr.indexOf("Infralist_" + lcb[2]);
markers.markers[theM].events.triggerEvent('mousedown');
};
};