我没有找到一种方法从DOM中获得扩展咏叹调的价值。
<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());
答案 0 :(得分:18)
aria-expanded
是元素的属性,而不是类,因此选择器不正确。其次,您应该使用attr()
函数来获取该属性的值。 val()
旨在从表单相关元素中检索value
属性,例如input
和textarea
。试试这个:
console.log($(this).find('a[aria-expanded]').attr('aria-expanded'));
答案 1 :(得分:4)
我想添加第二种纯JavaScript方式来获得aria-expanded属性
document.getElementById('test').getAttribute('aria-expanded')
上面将通过id获取元素,之后您可以通过名称获取任何属性。
答案 2 :(得分:2)
在2020年,我可以做到:
document.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')
获取第一个值,也许像这样:
Array.from(document.querySelectorAll('[aria-expanded]'))?
.map(el => el.getAttribute('aria-expanded'))
构成所有aria扩展值的数组。
答案 3 :(得分:1)
您可以使用JavaScript来实现此目的:
document.getElementsByTagName('a')[0].attributes[4].value
分步说明:
使用某个选择器获取所需元素 - 这里我使用
document.getElementsByTagName('a')[0]
但你可以使用你喜欢的任何其他选择器。
此方法的唯一问题是它有点硬编码,因此如果您向标记添加更多属性,则aria-expanded属性的attributes数组中的位置可能会更改。
答案 4 :(得分:0)
另一种获取 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'.