简体   繁体   中英

How do I target a looped element by Id with in the same loop?

This is what I'm trying to do:

var numArray = ["One","Two","Three","For","Five","Six"];

for (i = 0, i < numArray.length; i++) {
   document.getElementById('results').innerHTML += <div id='listResult_"+[i]+"'></div><br>;

   var target = document.getElementById('listResult_'+[i]);
   document.addDomListener(target, 'mouseover', function() {
      alert("listResult_"+[i]);
   });
}

It only alerts to the last target Id (listResult_5). How can I target all six individually?

Try:

for (i = 0, i < numArray.length; i++) {
   document.getElementById('results').innerHTML += "<div id='listResult_"+[i]+"'></div><br>";

   var target = document.getElementById('listResult_'+[i]);    

    (function(e) {
       document.addDomListener(target, 'mouseover', function() {
         alert("listResult_"+[e]);
       });
    })(i);
}

Every time you assign anything to innerHTML you destroy the elements in there already. Since you are using += you then create new elements… but the event handler you attached to them has been lost. Create and append elements with standard DOM methods instead.

Additionally, i is a variable. It will be whatever the last value it as assigned was when the loop has finished.

Get the data from context instead.

Your for loop syntax is also incorrect.

addDomListener appears to be a Google Maps feature. Use addEventListener for HTML.

var numArray = ["One","Two","Three","For","Five","Six"];

for (var i = 0; i < numArray.length; i++) {
   var myDiv = document.createElement('div');
   myDiv.id = "listResult_"+[i];
   myDiv.appendChild(document.createTextNode(myDiv.id));
   document.getElementById('results').appendChild(myDiv);
   // Don't append a line break between block containers. Use CSS isntead.
   myDiv.addEventListener('mouseover', function() {
      alert(this.id);
   });
}​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM