javascript - 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 时,没有添加类。
解决方案
像这样试试
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')
}
})
})
}
}
})
推荐阅读
- terminal - 有时当我打印到命令行时,我的代码会停止运行,直到我按下 control+c
- php - 使用用户定义的比较函数搜索 needle in_array
- netsuite - 如何修复:实体创建销售订单时出现“INVALID_FLD_VALUE”
- react-native - 在setState上反应本机TextInput闪烁
- r - R Dplyr解决方案summarize_at相关
- php - laravel登录控制器中的双重重定向
- apache - Apache Camel 在使用 setBody 插入数据之前进行验证
- php - 如何修复无法使用 jquery 检索数据
- reverse-proxy - HAProxy 将客户端 IP 转发到后端
- systemc - How do I stop a SystemC simulation, from a CTHREAD, and terminate the simulation with a specific exit code?