Javascript 如何使用 Jquery 如何更改 dom 元素(引导程序)的 aria-expanded="false" 部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27752210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:37:21  来源:igfitidea点击:

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

javascriptjqueryhtmlcsstwitter-bootstrap

提问by Bren

I have the following element:

我有以下元素:

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

I want to use jquery (or just javascript would work) to alter the aria-expanded field to toggle it between true and false.

我想使用 jquery(或仅使用 javascript)来更改 aria-expanded 字段以在 true 和 false 之间切换。

How would I go about this?

我该怎么办?

Thanks!

谢谢!

回答by gehleh

You can use .attr()as a part of however you plan to toggle it:

您可以使用.attr()作为您计划切换它的一部分:

$("button").attr("aria-expanded","true");

回答by volt

Since the question asked for either jQuery orvanilla JS, here's an answer with vanilla JS.

由于问题要求 jQueryvanilla JS,这里是 vanilla JS 的答案。

I've added some CSS to the demo below to change the button's font color to red when its aria-expandedis set to true

我在下面的演示中添加了一些 CSS 以在aria-expanded设置为红色时将按钮的字体颜色更改为红色true

const button = document.querySelector('button');

button.addEventListener('click', () => {
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);
})
button[aria-expanded="true"] {
  color: red;
}
<button type="button" aria-expanded="false">Click me!</button>