gpt4 book ai didi

Javascript 循环调用函数

转载 作者:行者123 更新时间:2023-12-03 06:15:22 25 4
gpt4 key购买 nike

尝试找出具有相同 ID 标签的多张图片的 onmouseover、onmouseout 和 onclick。为此,我知道我需要一个 .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;}
}

请指教,提前感谢您的帮助!

最佳答案

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;
}
}

关于Javascript 循环调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com