← 中文资源

简体中文版本

toggleAttribute 翻转布尔属性

toggleAttribute 切换布尔属性:无 force 参数时按当前状态翻转,传 true/false 可钉死结果,与总写字符串值的 setAttribute 语义不同。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:input。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 直接运行文件,输出会带上标签,比如 has checked:、after flip:、disabled set twice:——输出的每一行都能指回产生它的那次调用。

常见问题

「toggleAttribute 翻转布尔属性」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

input.setAttribute('aria-label', 'Accept terms');
const input = document.querySelector('#terms');
input.toggleAttribute('disabled', true);

代码示例

// Boolean-ish attributes: presence means on, absence means off
const input = document.querySelector('#terms');

// Without force, toggleAttribute flips the current state
input.toggleAttribute('checked');
console.log('has checked:', input.hasAttribute('checked'));

input.toggleAttribute('checked');
console.log('after flip:', input.hasAttribute('checked'));

// A force argument pins the outcome no matter what the state was
input.toggleAttribute('disabled', true);
input.toggleAttribute('disabled', true);
console.log('disabled set twice:', input.hasAttribute('disabled'));

// setAttribute always writes a string value; removeAttribute drops the node
input.setAttribute('aria-label', 'Accept terms');
input.removeAttribute('aria-label');
console.log('aria removed:', input.hasAttribute('aria-label'));