setAttribute没有更改值

时间:2018-05-24 13:34:49

标签: javascript dom

我有三个元素,我正在为每个元素尝试setAttribute:

const foldable = document.getElementsByClassName('foldable')
let result = Array.from(foldable)
result.forEach(i => {
 i.onclick = () => {
  i.getAttribute('isClicked') 
   ? i.setAttribute('isClicked', false)
   : i.setAttribute('isClicked', true)
 }
})

如果isClicked的值为true,则isClicked应该为false,否则如果isClicked的值为false,则isClicked应为true,但它只能运行一次。如果isClicked等于false,则isClicked不会更改为true。

1 个答案:

答案 0 :(得分:1)

您需要将三元运营商更新为以下

(i.getAttribute('isClicked') === "true")
   ? i.setAttribute('isClicked', false)
   : i.setAttribute('isClicked', true)

因为,如果属性为 false i.getAttribute('isClicked')会给出一个字符串"false",其评估为 true