gpt4 book ai didi

javascript - "Cannot read property ' classList ' of undefined"遍历 div 时出错 - Javascript

转载 作者:行者123 更新时间:2023-11-28 15:43:09 27 4
gpt4 key购买 nike

<分区>

我正在尝试在页面上切换 5 个圆圈(类为“圆圈”的 div),以便在单击事件监听器时更改背景颜色。

JavaScript:

var circle = document.querySelectorAll(".circle");

for(var i = 0; i < circle.length; i++){
circle[i].addEventListener('click', function(){
circle[i].classList.toggle('effect');
});

}

我不断收到错误消息“无法读取未定义的属性‘classList’”——我不确定为什么 circle 是未定义的?

CSS:

.circle {
width: 100px;
height: 100px;
border: solid 3px black;
border-radius: 100%;
float: left;
margin: 1%;
}


.effect {
background-color: green;
border-color: blue;

}

html:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>

<div class="circle">
</div>

<div class="circle">
</div>


<div class="circle">
</div>

<div class="circle">
</div>

<div class="circle">
</div>


<script src="script.js"></script>
</body>
</html>

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