【问题标题】:Add/Remove class of a nav ul li with jQuery by clicking href inside li通过单击 li 中的 href 使用 jQuery 添加/删除导航 ul li 的类
【发布时间】:2014-11-10 13:37:18
【问题描述】:

我有一个导航列表设置来显示/隐藏标签,它工作正常。我现在尝试仅在单击 href 的文本时添加/删除 nav ul li 项目的活动类。当前,当您单击列表项(文本周围的空间而不仅仅是文本)时,活动类会显示。因此,无需单击链接和更改选项卡即可显示活动类。

我已经尝试了很多变体来实现这一点,但没有结果。

<script>
  $(function(){
    $('#tabs li').click(function() {
    //Removes the active class from any <li> elements
    $('li.active').removeClass('active');
    //Adds it to the current element
    $(this).addClass('active');
    });
  }); 
</script>

HTML

<div class="warranty-nav">
  <ul id="tabs" class="nav">
    <li class="active"><a href="#overview">Overview</a></li>
    <li class=""><a href="#benefits">Plan Benefits</a></li>
    <li class=""><a href="#works">How It Works</a></li>
    <li class=""><a href="#terms">Terms and Conditions</a></li>
    <li class=""><a href="#faqs">Frequently Asked Questions</a></li>
  </ul>
</div>

提前致谢。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    试试这个:

     $('#tabs a').click(function() {
         //Removes the active class from any <li> elements
        $('#tabs li.active').removeClass('active');
        //Adds it to the current element
        $(this).parent('li').addClass('active');
      });
    

    【讨论】:

      【解决方案2】:
        $(function(){
          $('#tabs li').click(function() {
          //Removes the active class from any <li> elements
          $(this).siblings().removeClass('active');
          //Adds it to the current element
          $(this).addClass('active');
      });
        });
      
      • 删除同级类

      【讨论】:

        【解决方案3】:

        你的代码有效,你只需要关闭你的功能。

        <script>
          $(function(){
            $('#tabs li').click(function() {
            //Removes the active class from any <li> elements
            $('li.active').removeClass('active');
            //Adds it to the current element
            $(this).addClass('active');
          })});
        </script>
        

        【讨论】:

        • 如果页面中的其他li有活动类,如果使用上面的代码,它将被删除。检查负流。
        • @rpeki8 如果仅此而已,您可以在操作问题中添加评论。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多