我试图在单击按钮时在 true 和 false 之间切换 aria 标签。我已经尝试了几种实现,但似乎完全没有任何作用。以下是我当前正在使用的成功切换课程的内容。我如何扩展它以在 true 和 false 之间切换 aria-expanded 值?别介意,我正在从 jQuery 过渡到 ES6。
const theTrigger = document.getElementById('mobile-form-control');
const theForm = document.querySelectorAll('.l-header__mobile-form');
theTrigger.onclick = function () {
for (const x of theForm) {
x.classList.toggle('show');
}
};
通过简单的切换会更容易:
x.ariaExpanded = !x.ariaExpanded;
但奇怪的是,Firefox 不支持对 DOM 属性的直接布尔访问! 🤯 https://developer.mozilla.org/en-US/docs/Web/API/Element/ariaExpanded#browser_compatibility
所以我最终得到了这样的结果:
x.setAttribute(
'aria-expanded',
`${!(x.getAttribute('aria-expanded') === 'true')}`
);
假设 for 循环中的
x
是您想要切换 aria-expanded
属性的元素:
theTrigger.onclick = function () {
for (const x of theForm) {
x.classList.toggle('show');
x.setAttribute(
'aria-expanded',
`${(x.getAttribute('aria-expanded') !== 'true').toString()}`
);
}
};