【问题标题】:False True change attr by onclick jQueryFalse True 通过 onclick jQuery 更改属性
【发布时间】:2017-11-29 20:30:45
【问题描述】:

我需要通过 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>

【问题讨论】:

    标签: javascript jquery onclick toggle attr


    【解决方案1】:
    if ($(this).attr('aria-selected')) {
    

    应该是

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

    您在页面加载时将 aria-selected 明确设置为 false。当单击具有accordion 类的元素时,您似乎切换了属性值。但在您的情况下,由于您现有的 if 条件,它将始终设置为 false。

    您可以修改代码以使其更简洁

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

    【讨论】:

      【解决方案2】:

      aria-selected 是一个字符串...不是布尔值。
      所以你必须将它与一个字符串进行比较。

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

      【讨论】:

        猜你喜欢
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-09
        • 1970-01-01
        • 2021-06-26
        • 2012-08-28
        • 1970-01-01
        相关资源
        最近更新 更多