首页 > 解决方案 > 无法使用 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 组件的一部分

标签: javascripthtmlvue.js

解决方案


您可以尝试获取元素的 id 并相应地更改整个类,而不是使用上面的方法:

var element = document.getElementByID("element");
element.className = the_classname_you_desire;

或者

您可以尝试通过以下方式获取元素的 id 并相应地添加类的类型:

var element = document.getElementByID("element");
element.className += the_classname_you_desire;

希望这种替代方法能满足您的编码需求。


推荐阅读