【问题标题】:Cannot change element class with JS无法使用 JS 更改元素类
【发布时间】: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


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    相关资源
    最近更新 更多