gpt4 book ai didi

Javascript - 未捕获的类型错误 : Cannot read property 'classList' of null

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

如何检查我点击的元素是否有类列表?

let dropdown  = target.nextElementSibling.classList.contains('form__select-dropdown')

当我单击的元素没有附加到它的类时,我的代码在此行出错。

这是完全有道理的。

但是,如果 nextElementSibling 具有类 form__select-dropdown,我只希望下面的代码运行:

        if (!selectTag && dropdown) {
target.querySelector('.form__select-dropdown').classList.remove('active')
} else {
target.nextElementSibling.classList.toggle('active')
}

所以我需要在执行条件之前检查 target.nextElementSibling.classList 是否存在以避免错误,但我不确定该怎么做?

最佳答案

您的问题是 target 并不总是有 nextElementSibling;在继续之前,您应该检查它是否为 null

let next = target.nextElementSibling
let dropdown = next && next.classList.contains('form__select-dropdown')

稍后在您的代码中:

    if (!selectTag && dropdown) {
target.querySelector('.form__select-dropdown').classList.remove('active')
} else {
next && next.classList.toggle('active')
}

关于Javascript - 未捕获的类型错误 : Cannot read property 'classList' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42414509/

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