Javascript循环调用函数

时间:2016-08-24 17:00:08

标签: javascript loops onmouseover onmouseout

尝试找出onmouseover,onmouseout和onclick,其中几张图片都具有相同的ID标签。要做到这一点,我知道我需要一个.length循环。

此代码无需长度循环...

window.onload = setPictures;
function setPictures() {
    var img = document.getElementById("pictureBox");
        img.onmouseover = mouseOverImage;
        img.onmouseout= mouseOutImage; 
}
function mouseOverImage() {
    var img = document.getElementById("myImg");
    img.style.opacity = .5;
}
function mouseOutImage() {
    var img = document.getElementById("myImg");
    img.style.opacity = 1;
}

这是我尝试的循环功能无效。

window.onload = setPictures;
function setPictures() {
   var img = document.getElementById("pictureBox");
   for (var i=0; i<img.length; i++) {       
      img[i].onmouseover = mouseOverImage;
      img[i].onmouseout= mouseOutImage;}
 }

请提前告知,并提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

getElementById只返回一个元素,因为ID应该是唯一的。

相反,为每个元素添加一个类并按类选择它们。回调可以依赖this的上下文来处理鼠标事件:

function mouseOverImage() {
    this.style.opacity = .5;
}
function mouseOutImage() {
    this.style.opacity = 1;
}

window.onload = function setPictures() {
    var imageCollection = document.getElementsByClassName('pictureBox');
    for (var i=0; i < imageCollection.length; i++) {       
        imageCollection[i].onmouseover = mouseOverImage;
        imageCollection[i].onmouseout = mouseOutImage;
    }
 }

答案 1 :(得分:0)

如前所述,getElementById只返回一个元素 以下内容可以帮助您:

window.onload = setPictures;
    function setPictures() {
       var img = document.getElementById("pictureBox0");
       for (var i=1; img != null; i++) {       
          img.onmouseover = mouseOverImage;
          img.onmouseout= mouseOutImage;
          img = document.getElementById("pictureBox"+i);
       }
     }