.apply 与 classList.remove 一起应用时抛出异常

Raj*_*esh 2 javascript dom domtokenlist

我正在尝试一些东西并遇到了这个问题。当您尝试执行时element.classList.remove.apply,它会引发错误:

未捕获的类型错误:非法调用

您可以使用以下代码段对其进行测试。

var div = document.querySelector('.test');
var classesToRemove = ['test1', 'test2', 'test3'];
div.classList.remove.apply(div, classesToRemove);
Run Code Online (Sandbox Code Playgroud)
.test {
  width: 100px;
  height: 100px;
}

.test1 {
  color: blue
}

.test2 {
  background: gray;
}

.test3 {
  border: 1px solid gray;
}
Run Code Online (Sandbox Code Playgroud)
<div class='test test1 test2 test3'>Test</div>
Run Code Online (Sandbox Code Playgroud)


注意:我知道我可以使用扩展运算符 ( ...)来解决这个问题,但我对理解为什么会失败更感兴趣。

dfs*_*fsq 5

您也可以在这里使用 Function.prototype.apply,但是正确的调用上下文是div.classList对象,而不是 HTMLElementdiv本身。

尝试这个:

var div = document.querySelector('.test');
var classesToRemove = ['test1', 'test2', 'test3'];
div.classList.remove.apply(div.classList, classesToRemove);
Run Code Online (Sandbox Code Playgroud)
.test {
  width: 100px;
  height: 100px;
}

.test1 {
  color: blue
}

.test2 {
  background: gray;
}

.test3 {
  border: 1px solid gray;
}
Run Code Online (Sandbox Code Playgroud)
<div class='test test1 test2 test3'>Test</div>
Run Code Online (Sandbox Code Playgroud)