如何使用纯 JavaScript 切换元素的属性?

mur*_*u27 5 html javascript

大多数所出现的,我写这一个是像类似的问题(用户希望使用纯JS来切换元素的类)或(用户希望愿望切换使用jQuery等属性)

我的问题是两者的混合。I am aware that the el.classList.toggle()method exists for toggling an element's class using pure JS, but I wish to toggle different attributes using pure JS, specifically the checkedattribute of some radio buttons, since this (annoyingly) does not change when different options are selected.

是否可以checked使用纯 JS 切换我的两个单选按钮上的属性(通过切换,我的意思是如果存在则从元素中完全删除该属性,如果不存在则添加它)?

radios = document.getElementsByName("Floor");
for (i = 0; i < radios.length; i++) {
    radios[i].addEventListener('change', function () {
        this.(/*checked attribute*/).toggle()
    }, false);
}
Run Code Online (Sandbox Code Playgroud)
<input checked id="Floor" name="Floor" type="radio" value="0">Ground Floor
<input id="Floor" name="Floor" type="radio" value="1">First Floor
Run Code Online (Sandbox Code Playgroud)

编辑:评论中提到的可能重复的问题并不能完全解决我的问题。我不需要更改哪个单选按钮显示为选中状态,我只想切换checked属性,以便我更轻松地引用稍后在代码中选中的按钮。当然,如果有另一种更简单的方法来做到这一点,我全都在听。

Men*_*ndy 5

实际上有一种Element.toggleAttribute布尔属性的方法。MDN 文档

但是,由于 IE 不支持它,您可能需要添加MDN Polyfill


Nic*_*ens 1

我没有测试这个,但这应该可以解决问题。

radios = document.getElementsByName("Floor");
  for (i = 0; i < radios.length; i++) {
    radios[i].addEventListener('change', function () {
       if ( this.checked ) {
          this.setAttribute("checked", "false");
       } else {
          this.setAttribute("checked", "true");
       }
  }, false);
}
Run Code Online (Sandbox Code Playgroud)