首页 > 解决方案 > jQuery addClass 工作,但 javascript classList.add 不工作

问题描述

我正在尝试通过 javascript 添加一个类,但它没有在我的 DOM 中更新。当我使用 jQuery 时,虽然一切都按预期工作。问题是添加 svg--active 类不起作用。item.classList.add('tab-brackground--active') 有效。

我的 jQuery 代码 -

window.addEventListener('load', function () {
    const svg = document.querySelector('svg')

    if (svg) {
        const items = document.querySelectorAll(
            '.woocommerce-grouped-product-list-item'
        )

        if (items) {
            items.forEach((item) => {
                item.addEventListener('mouseenter', (e) => {
                    item.classList.add('tab-brackground--active')
                    const text = e.target.children[0].innerText
                    jQuery(`[data-section="${text.toLowerCase()}"]`).addClass(
                        'svg--active'
                    )
                })
            })
        }
    }
})

用 javascript 做的同样的事情不起作用 -

window.addEventListener('load', function () {
    const svg = document.querySelector('svg')

    if (svg) {
        const items = document.querySelectorAll(
            '.woocommerce-grouped-product-list-item'
        )

        if (items) {
            items.forEach((item) => {
                item.addEventListener('mouseenter', (e) => {
                    item.classList.add('tab-brackground--active')
                    const text = e.target.children[0].innerText
                    document.querySelector(`[data-section="${text.toLowerCase()}"]`).classList.add(
                        'svg--active'
                    )
                })
            })
        }
    }
})

当我 console.log 我的 javascript 元素时,它显示了添加了类的元素,但是当我去检查 DOM 时,没有添加类。

标签: javascriptjquerycsswordpress

解决方案


像这样试试

window.addEventListener('load', function () {
    const svg = document.querySelector('svg')

    if (svg) {
        const items = document.querySelectorAll(
            '.woocommerce-grouped-product-list-item'
        )

        if (items) {
            items.forEach((item) => {
                item.addEventListener('mouseenter', (e) => {
                    item.classList.add('tab-brackground--active')
                    const text = e.target.children[0].innerText
                    const nodeList = document.querySelectorAll(`[data-section="${text.toLowerCase()}"]`);
                    for(let i=0 ;i<nodeList.length; i++) {
                      nodeList[i].classList.add('svg--active')
                    }
                })
            })
        }
    }
})


推荐阅读