[英]jQuery addClass working but javascript classList.add not working
我正在嘗試通過 javascript 添加 class 但它沒有在我的 DOM 中更新。 當我使用 jQuery 時,盡管一切都按預期工作。 問題是添加 svg--active class 不起作用。 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 元素時,它顯示了添加了 class 的元素,但是當我 go 檢查 DOM 時,沒有添加 ZA2F221ED4F8EBC29ABCD29。
試試這樣,
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') } }) }) } } })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.