【发布时间】:2020-10-11 02:58:33
【问题描述】:
我正在尝试使用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 组件的一部分
【问题讨论】:
-
你为什么要为此使用方法或类?您可以使用 v-if 有条件地显示元素并使用鼠标事件来切换数据中的变量。你熟悉 Vue 的工作原理吗?
-
@JHeth 当然,你更擅长 Vue,但问题不在于如何使用数据中的变量来做到这一点。如果您对给定的问题无话可说 - 将您的建议留给自己。问题不在于如何以其他方式实施。
-
不看完整代码很难说出原因。请问你为什么要这样做而不是
:class="{hide: status == 'x' || status == 'y'}"
标签: javascript html vue.js