简体   繁体   中英

For Loop in Javascript (document.getElementById)

I have a little Javascript problem. Instead of using this:

document.getElementById("hoverinv1").style.display = "";
document.getElementById("hoverinv2").style.display = "";
document.getElementById("hoverinv3").style.display = "";
document.getElementById("hoverinv4").style.display = "";
document.getElementById("hoverinv5").style.display = "";
document.getElementById("hoverinv6").style.display = "";
document.getElementById("hoverinv7").style.display = "";
document.getElementById("hoverinv8").style.display = "";
document.getElementById("hoverinv9").style.display = "";
document.getElementById("hoverinv10").style.display = "";

I wanted to use this:

for (var x = 0; x < 11; x++) {
    document.getElementById("hoverinv" + x).style.display="";
}

To display again everything. Well, it does nothing and I have no idea whats the problem.

It's probably throwing an error on the first iteration because hoverinv0 does not exist. You want

for (var x = 1; x < 11; x++) {
  document.getElementById("hoverinv" + x).style.display="";
}

Do it simply in CSS:

[id^=hoverinv] {
  display: block; /* or any other needed display value */
}

Your issue: by inspecting your JS in Console you can clearly see that it breaks while fetching your hoverinv0 ID element ( does not exists ).

What you can:

assign a class class="hoverinv" to all your element and go for:

var hoverInv = document.getElementsByClassName("hoverinv");
for (var i=0; i<hoverInv.length; i++){
     hoverInv[i].style.display = "";
}

or using

var hoverInv = document.querySelectorAll("[id^=hoverinv]");
for (var i=0; i<hoverInv.length; i++){
     hoverInv[i].style.display = "";
}

or something you might go fix all over again as soon you change the number of elements :

for(var i=1; i<11; i++){
   document.getElementById("hoverinv"+ i).style.display = "";
}

Your first code starts with "hoverinv1" and in your loop you start with "hoverinv0" .

Probably, it is not finding the element, returning undefined and then your script crashes when you try to access style property.

Check the browser's console, it should emit an error or something.

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