gpt4 book ai didi

javascript - 未捕获的 TypeError : Cannot read property 'classList' of null | But points to the element when I console. 记录它

转载 作者:行者123 更新时间:2023-11-30 08:22:26 25 4
gpt4 key购买 nike

当我 console.log target.nextElementSibling 时,它指向正确的元素。但是当我尝试添加 ".d_on"target.nextElementSibling

var ul = document.querySelector(".images");
var img_li = document.querySelectorAll(".img_li");
var pointer = document.querySelector(".d_on");
var left = document.querySelector(".left");
var right = document.querySelector(".right");

right.addEventListener("click",function(){
img_li.forEach(element => {
if(element.classList.contains("d_on")){
element.classList.remove("d_on");
var nextElem = element.nextElementSibling;
console.log(nextElem);
nextElem.classList.add("d_on");
}
});
});//end of event

<body>
<div id="img-nav">
<a href="#" class="arrow left"><img src="img/left.png"></a>
<a href="#" class="arrow right"><img src="img/right.png"></a>
</div>

<ul id="images">
<li class="img_li d_on"><img src="img/1.jpg"></li>
<li class="img_li "><img src="img/2.jpg"></li>
<li class="img_li"><img src="img/3.jpg"></li>
<li class="img_li "><img src="img/4.jpg"></li>
<li class="img_li"><img src="img/5.jpg"></li>
<li class="img_li"><img src="img/6.jpg"></li>
<li class="img_li"><img src="img/7.jpg"></li>
<li class="img_li"><img src="img/8.jpg"></li>
</ul>
</body>

最佳答案

为下一个元素添加空检查

if (nextElem != null) {  
nextElem.classList.add("d_on");
}
//Note: nextElem!= null checks for both null and undefined.

关于javascript - 未捕获的 TypeError : Cannot read property 'classList' of null | But points to the element when I console. 记录它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219770/

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