我需要通过oncklick更改数据属性“aria-selected” 但是这个脚本不起作用。你能帮帮我吗?
<a href="#" aria-selected="true" resource="">SHOW/HIDE</a>
这是我的代码:
<script>
$(document).ready(function($){
$("a").attr("aria-selected","false");
$(" ul li a").addClass("accordion");
$('.accordion').click(function() {
if ($(this).attr('aria-selected')) {
$(this).attr("aria-selected","true");
}
else {
$(this).attr("aria-selected", "false");
}
});
});
</script>
答案 0 :(得分:2)
if ($(this).attr('aria-selected')) {
应该是
if ( !$(this).attr('aria-selected') ) {
您在页面加载时明确将aria-selected
设置为false。单击具有accordion
类的元素时,您似乎切换了属性值。但在您的情况下,它将始终设置为false,原因是您现有的if
条件。
您可以修改代码以使其更清晰
$("a").attr("aria-selected", "false");
$(" ul li a").addClass("accordion");
$('.accordion').click(function(e) {
e.preventDefault();
var $this = $(this);
var currentValue = $this.attr('aria-selected');
$this.attr('aria-selected', !(currentValue === 'true'));
});
[aria-selected="true"] {
color: green;
}
[aria-selected="false"] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a href="#" aria-selected="true" resource="">SHOW/HIDE</a>
</li>
<li>
<a href="#" aria-selected="true" resource="">SHOW/HIDE</a>
</li>
<li>
<a href="#" aria-selected="true" resource="">SHOW/HIDE</a>
</li>
</ul>
答案 1 :(得分:2)
dynamic
是一个字符串......不是布尔值
所以你必须将它与一个字符串进行比较。
aria-selected