开发者问题收集

未捕获的 TypeError:无法读取 null 的属性“classList”|但当我 console.log 它时指向该元素

2018-07-07
776

当我 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>
2个回答

为 nextElement 添加空检查

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

按照 Patrick 的提示,尝试添加

if (nextElem) {
    nextElem.classList.add("d_on");
}
delki8
2018-07-07