简体   繁体   English

Java语言中的For循环(document.getElementById)

[英]For Loop in Javascript (document.getElementById)

I have a little Javascript problem. 我有一个Javascript问题。 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. 因为hoverinv0不存在,所以可能在第一次迭代时抛出错误。 You want 你要

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

Do it simply in CSS: 只需在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 ). 您的问题:通过在控制台中检查JS,您可以清楚地看到它在获取hoverinv0 ID元素( 不存在 )时破裂。

What you can: 你能做什么:

assign a class class="hoverinv" to all your element and go for: 为您的所有元素分配一个class class="hoverinv"并进行以下操作:

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" . 您的第一个代码以"hoverinv1"开头,并且在循环中以"hoverinv0"开头。

Probably, it is not finding the element, returning undefined and then your script crashes when you try to access style property. 可能是找不到元素,返回undefined ,然后在尝试访问style属性时脚本崩溃。

Check the browser's console, it should emit an error or something. 检查浏览器的控制台,它应该发出错误或其他信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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