False True change attr by onclick jQuery

 ̄綄美尐妖づ 提交于 2019-12-11 04:25:26

问题


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>

回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/44769223/false-true-change-attr-by-onclick-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!