0

I'm trying to change the classes of multiple siblings upon a click event, some of them might have multiple classes to each, but the class that I intend to change is always the first one, so that is what I came with

let classList = event.currentTarget.classList;
    if (classList[0] === 'open'){
      classList[0] = 'close';
      event.currentTarget.classList = classList;
      return;
    }
    let sibllingList = event.currentTarget.parentElement.children;
    for (let i=0;i<sibllingList.length;i++) {
      classList = sibllingList[i].classList;
      if (classList[0] === 'open') {
        classList[0] = 'close';
        sibllingList[i].classList = classList;
        break;
      }
    }
    classList = event.currentTarget.classList;
    if (classList[0] === 'close'){
      classList[0] = 'open';
      event.currentTarget.classList = classList;
    }

This worked when I was working with a single class and using className instead of classList, and the function worked fine, but when I switched it to classList, it didn't work and threw the following error

Uncaught TypeError: Failed to set an indexed property on 'DOMTokenList': Index property setter is not supported.

4

2 回答 2

1

classList是一个只读属性。所以,你不能给它赋值。所以,你得到错误:

未捕获的类型错误:无法在“DOMTokenList”上设置索引属性:不支持索引属性设置器。

您需要添加该类:

event.currentTarget.classList.add('close')

要删除类,请使用 remove:

event.currentTarget.classList.remove('open')

这样您就不需要检查第一类名称。它将添加/删除所需的类名。

注意:删除不存在的类不会引发错误。

或者,您可以只使用替换:

event.currentTarget.classList.replace('open', 'close')
于 2019-02-21T16:13:34.890 回答
0

这是一个尝试看看

var classList = test.classList;
    if (classList[0] === 'open'){
        test.classList.replace('open', "close");
      //event.currentTarget.classList = classList; // dont need this 
    }
    console.log( test.classList)
<div id="test" class="open b test"> <div/>

于 2019-02-21T16:19:21.843 回答