False True change attr by onclick jQuery

2019-08-02 08:17发布

I need to change data attribute "aria-selected" by oncklick.
But this script does not work. Could you help me, please?

<a href="#" aria-selected="true" resource="">SHOW/HIDE</a>

And here is my code:

<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>

2条回答
forever°为你锁心
2楼-- · 2019-08-02 08:44

The aria-selected is a string... Not a boolean.
So you have to compare it with a string.

<script>
$(document).ready(function($){
  $("a").attr("aria-selected","false");
  $(" ul li a").addClass("accordion");

  $('.accordion').click(function() {
    if ($(this).attr('aria-selected') == "false") {  // Change is here.
      $(this).attr("aria-selected","true");
    } 
    else {
      $(this).attr("aria-selected", "false");
    }
  });
});
</script>
查看更多
淡お忘
3楼-- · 2019-08-02 08:47
if ($(this).attr('aria-selected')) {

is supposed to be

if ( !$(this).attr('aria-selected') ) {

You are explicitly setting aria-selected to false on page load. When the element with accordion class is clicked, you seem to toggle the attribute value. But in your case it will always be set to false, cause of your existing if condition.

You can modify the code to make it a bit cleaner

$("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>

查看更多
登录 后发表回答