javascript - 通过 ID 切换元素的类

标签 javascript jquery html css toggle

我试图在单击元素时将其类从一个值 A 更改为值 B,然后在第二次单击时从值 B 变回值 A。我在这里找到了一些代码,允许我更改一次,但不能更改第二次。 (参见原文 here)。

原代码如下:

<script type="text/javascript">
  function changeClass() {
    document.getElementById("MyElement").className += " MyClass";
    document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g, '')
  }
</script>

这是我的代码:

<script type="text/javascript">
  function changeClass() {
    if (document.getElementByID("arrow").className == "arrowdown") {
      document.getElementById("arrow").className.replace(/(?:^|\s)arrowdown(?!\S)/g, 'arrowup')
    }
    elseif(document.getElementByID("arrow").className == "arrowup") {
      document.getElementById("arrow").className.replace(/(?:^|\s)arrowup(?!\S)/g, 'arrowdown')
    }
  }
</script>

最佳答案

$('#arrow').toggleClass('arrowup arrowdown');

关于javascript - 通过 ID 切换元素的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12522723/

相关文章:

javascript - 输入值不会改变

javascript - 异步地理定位 API 和 jQuery 延迟对象

javascript - 如何在剑道散点线系列类型的 x 轴上添加完整日期

html - 如何在 css 中模糊我的背景图像?

html - 有没有办法指定图像的最大高度或宽度?

javascript - Angular Js ng-controller 未填充该值

javascript - 是否存在任何已知的 HTA 文件安全问题?

javascript - Select2 仅通过 id 设置选定值

javascript - jQuery .each()、.find() 和 .append() 仅适用于最后一个节点?

javascript - Bootstrap 折叠按钮在单击时不显示内容