gpt4 book ai didi

Javascript - 不适用于每个循环

转载 作者:行者123 更新时间:2023-11-30 14:46:35 25 4
gpt4 key购买 nike

<分区>

我的 foreach 循环有问题。使用 foreach 循环的书面代码不起作用,但如果我使用 for 循环,一切都会正常工作。我在互联网上寻找解决方案几个小时却一无所获。我举两个例子。第一个例子是使用 foreach 循环,第二个例子是使用 for 循环。抱歉,我的英语不是最好的。

示例 - foreach 循环(损坏):

window.onload = () => {
test();
};


function test() {
let testDiv = Array.from(document.getElementsByClassName("test"));
let currentTest = testDiv[0];
currentTest.className += " test2";
testDiv.forEach((current) => {
current.addEventListener('mousemove', () => {
currentTest.className = currentTest.className.replace("test2", "");
currentTest = this;
currentTest.className += " test2";
});
});
}
.test {
width: 50px;
height: 50px;
float: left;
cursor: pointer
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css"/>
<script src="js/script.js" async></script>
</head>
<body>
<div>
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
</div>
</body>
</html>

示例 - for 循环(工作正常):

window.onload = () => {
test();
};


function test() {
let testDiv = Array.from(document.getElementsByClassName("test"));
let currentTest = testDiv[0];
currentTest.className += " test2";
for (var i = 0; i < testDiv.length; i++) {
testDiv[i].onmouseover = function() {
currentTest.className = currentTest.className.replace("test2", "");
currentTest = this;
currentTest.className += " test2";
};
}
}
.test {
width: 50px;
height: 50px;
float: left;
cursor: pointer
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css"/>
<script src="js/script.js" async></script>
</head>
<body>
<div>
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
</div>
</body>
</html>

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