【问题标题】:Is it possible in JS to add to an html element some classes and remove some other classes in one line?是否可以在 JS 中向 html 元素添加一些类并在一行中删除一些其他类?
【发布时间】:2020-11-02 00:55:14
【问题描述】:

想知道是否有任何与some_element.classList.add("some_class", "some_other_class).remove("some_other_other_class") 行等效的功能。

而且我知道.toggle() 方法在某些情况下是一种解决方案,但我想知道是否有一种方法可以在一行中完全使用.add().remove()

【问题讨论】:

  • 你为什么需要它?
  • @VaheYavrumian 观察 JS 在一行上完成多项任务的能力。例如,我们可以在一行上执行 array.filter().sort().map() 。也许它可以对类的方法做同样的事情。

标签: javascript html class methods


【解决方案1】:

您可以这样做来添加和删除多个类。

const header = document.getElementById('header');

const addClasses = ['foo', 'bar', 'hello'];
const removeClasses = ['class1'];

header.className = header.className.split(' ')
                         .filter(c => !removeClasses.includes(c))
                         .concat(addClasses).join(' ');

// to show the classes on the #header element
document.body.innerHTML = header.className;             
<h1 id="header" class="class1 class2 class3"></h1>

【讨论】:

  • 感谢您对任务的承诺。该代码应该可以工作。我想虽然我希望有一些语法技巧。就像 html 的那个 emmet 一样,符号“^”让你从标签“爬上”并继续写其他命令。想知道是否有同样的事情要做.add(),然后“爬回”到 classList,然后做 .remove()。我想到目前为止还没有这样的事情。
  • 想知道是否有同样的事情要做。add() 然后“爬回”到 classList 然后做 .remove() - 你不能那样做因为.add() 方法返回undefined
【解决方案2】:

是的,你可以使用 classList.replace() 方法

element.classList.replace('some-class', 'new-class');

【讨论】:

  • 那时我意识到我没有很好地说明我的问题。当然,.replace() 也解决了一些情况,但是说我需要添加一些和删除一些,这就是我不知道我是否可以在一行中完成的地方。我应该具体说明问题。谢谢)
  • 可能是一个函数并将参数传递给 replace 方法?
  • 感觉结束并不能证明这里的手段是合理的,但我认为这会奏效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
相关资源
最近更新 更多