繁体   English   中英

获取 aria 扩展值

[英]Get aria-expanded value

我没有找到从 DOM 中获取 aria-expanded 值的方法。

<a class="accordion-toggle collapsed" href="#collapse-One" data-parent="#accordion-1" data-toggle="collapse" aria-expanded="false">
    <i class="fa fa-search-plus"></i>
    test
</a>

我想测试它是否true然后我可以将<i>类更改为fa-search-minus 我试过这个,但我总是得到一个未定义的值:

console.log($(this).find('a.aria-expanded').val());

aria-expanded是元素上的一个属性,而不是一个类,所以选择器是不正确的。 其次,您应该使用attr()函数来获取该属性的值。 val()旨在从与表单相关的元素(例如inputtextarea val()中检索value属性。 尝试这个:

console.log($(this).find('a[aria-expanded]').attr('aria-expanded'));

我想添加第二种纯 javascript 方式来获取 aria-expanded 属性

document.getElementById('test').getAttribute('aria-expanded')

上面将通过 id 获取元素,然后您可以通过名称获取任何属性。

您可以使用 JavaScript 来实现这一点:

document.getElementsByTagName('a')[0].attributes[4].value

分步说明:

  1. 通过使用一些选择器获取想要的元素 - 在这里我使用

    document.getElementsByTagName('a')[0]

但您可以使用任何其他您喜欢的选择器。

  1. 访问元素的属性数组并找到所需属性的位置 - 在本例中为 4,因为 aria-expanded 是标签的第 5 个属性。
  2. 从那里你只得到值,这应该给你“假”(在这种情况下)。

此方法的唯一问题是它有点硬编码,因此如果您向标记添加更多属性,则 aria-expanded 属性在属性数组中的位置可能会发生变化。

更新

您可以使用名称,而不是使用索引来访问 Aria Expanded 属性:

document.getElementsByTagName('a')[0].attributes['aria-expanded'].value

这样您将始终获得 Area Expanded 属性的值,而不管它在 HTML 标记中的位置。

2020年,我可以做到:

document.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')

获取第一个值,可能类似于:

Array.from(document.querySelectorAll('[aria-expanded]'))?
  .map(el => el.getAttribute('aria-expanded'))

制作一个包含所有 aria 扩展值的数组。

获取 aria 值的另一种方法是直接引用属性:

对于您的实例,您可以执行以下操作:

let firstAnchorTag = document.getElementsByTagName('a')[0]; // I don't know your situation but I recommend adding an id to this element, or making this an iterable array.
console.log(firstAnchorTag.ariaExpanded); // Should log 'false' for your example.

要得到:

let el = document.getElementById('foobar');
console.log(el.ariaExpanded); // Should log the current value of aria-expanded.

设置:

let el = document.getElementById('foobar');
el.ariaExpanded = 'true';
console.log(el.ariaExpanded); // Should log 'true'.

参考: Element.ariaExpanded MDN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM