开发者问题收集

Javascript 通过 onmouseover 类进行迭代

2021-05-02
90

我想遍历一个类,并在将鼠标悬停在每个元素上时显示相应的文本。

HTML

<div class="box red"></div>

<div class="box green"></div>

<div class="box red"></div>

<div class="info">
Hi
</div>

<div class="info">
Hello
</div>

<div class="info">
Hey
</div>

CSS

.box {
  width:100px; 
  height:100px;
  border-radius: 10px;
}

.red{
  background-color: red;
}

.green{
  background-color: green;
}

.info {
  display: none;
}

Javascript

var box = document.getElementsByClassName("box");

for (var i = 0; i < box.length; i++) {
  box[i].onmouseover = function(){
    var info = document.getElementsByClassName("info");
    info[i].style.display= "block";
  }
}

for (var i = 0; i < box.length; i++) {
box[i].onmouseout = function(){
  var info = document.getElementsByClassName("info");
  info[i].style.display= "block";
  }
}

我收到错误

Uncaught TypeError: Cannot read property 'style' of undefined"

如果我用 <id> 设置每个 <div> ,然后一遍又一遍地重复我的代码,它就会起作用。为什么我迭代后它不起作用?

https://jsfiddle.net/4q8jrt2m/2/

2个回答

这对我有用:

var box = document.getElementsByClassName("box");
var info = document.getElementsByClassName("info")
for (var i = 0; i < box.length; i++) {
box[i].onmouseover = show(i);
box[i].onmouseout = hide(i);
}



function show(index){
return ()=>{info[index].style.display='block'
}}

function hide(index){
return ()=>{info[index].style.display='none'
}}
I3B
2021-05-02

事件划线 我会说的。类似:

476386376
KooiInc
2021-05-02