javascript - 无法使用 JS 更改元素类
问题描述
我正在尝试使用JS更改按钮内的span元素的类,控制台显示类中的更改,但实际上该类没有更改。
元素html:
<button
type="button"
:class="`btn btn-link link ${status === 'x' ? 'primary' : 'danger'} ${className}`"
@mouseenter="switchText"
@mouseleave="switchText"
>
<span :id="first-button-id">
sometext
</span>
<span :id="second-button-id" class="hide">sometext1</span>
</button>
JS:
const firstButton = document.getElementById('first-button-id')
const secondButton = document.getElementById('second-button-id')
if (e.type === 'mouseenter') {
if (this.status === 'x' || this.status === 'y') {
firstButton.classList.toggle('hide')
secondButton.textContent = 'sometext'
secondButton.classList.toggle('hide')
console.log(firstButton.classList, secondButton.classList)
} else if (e.type === 'mouseleave') {
firstButton.classList.toggle('hide')
secondButton.classList.toggle('hide')
console.log(firstButton.classList, secondButton.classList)
}
}
我还尝试通过浏览器中的控制台进行更改 - 遇到了同样的问题。
如果重要,按钮是 Vue 组件的一部分
解决方案
您可以尝试获取元素的 id 并相应地更改整个类,而不是使用上面的方法:
var element = document.getElementByID("element");
element.className = the_classname_you_desire;
或者
您可以尝试通过以下方式获取元素的 id 并相应地添加类的类型:
var element = document.getElementByID("element");
element.className += the_classname_you_desire;
希望这种替代方法能满足您的编码需求。
推荐阅读
- node.js - MongoDB减慢插入包含嵌套数组的数据
- python - VScode python 3 pylint:我可以在A中导入X文件,但不能在B中导入
- javascript - 从输入类型 =“时间”添加/编辑时间
- c++ - 对于相同的任务,为什么更多的线程导致更少的指令
- internet-explorer - webdriverio browser.executeAsync 在 IE11 中抛出错误设置参数
- c# - 更改多维数组中的一个属性也会更改其他数组的属性
- javascript - 正则表达式只允许输入字段中的字母和空格,但第一个字符不应该是空格
- authentication - 如何延长 TFS 访问的身份验证寿命?
- c# - 在屏幕中央添加`UIImageView`
- unity3d - Unity3D 中的 LWRP 后处理效果不可见