【问题标题】:How to use jQuery to style active link list items如何使用 jQuery 设置活动链接列表项的样式
【发布时间】:2020-02-24 01:06:53
【问题描述】:

我正在使用 jQuery 检查浏览器 URL 是否与我的链接 href 中的 URL 匹配,问题是在我检查后我试图将链接匹配的 li 标记类设置为“活动”,但下面的代码正在将链接标签设置为活动而不是 li 标签

    $(function(){
        var current = location.pathname;
        $('#nav li a').each(function(){
            var $this = $(this);
            // if the current path is like this link, make it active
            if($this.attr('href') === current){
                $this.addClass('active');
            }
        })
    }) 

【问题讨论】:

  • 由于您没有显示代码(由于高级商标和版权原因),您可以显示console.log(current);console.log($this);。? ...也就是说,即使您认为这不是一种态度,也请展示您的代码。
  • 我建议在提问时使用更具描述性的标题。有那么一刻,我认为这是一个类似于“何时使用 jQuery?”的问题。几乎结束了主要基于意见的问题..
  • 您的“this”指的是 a href 而不是 li。首先查找当前的所有 attr href,然后设置每个父 li 的样式。
  • @icecub np 我编辑了问题,重新阅读并更改了我的评论。

标签: javascript jquery html css dom


【解决方案1】:

this 指的是 a 元素,而不是您认为的 li,它实际上是当前元素的父元素 (a) .

你必须定位parent()

$this.parent().addClass('active');

或者:使用.closest()

$this.closest('li').addClass('active');

【讨论】:

    【解决方案2】:

    你好

    你可以试试这个

    $(document).ready(function () {
    
      $(".nav li").click(function () {
        $(".nav li").removeClass("active");
        $(this).addClass("active");
      });
    
    });
    .headerTopMenu ul {
        padding: 0;
        margin: 0;
        list-style: none;
    }
    
    .headerTopMenu li {
        display: inline-block;
        padding: 0 15px;
    }
    .headerTopMenu li a {
        display: inline-block;
        text-decoration: none;
        font-size: 16px;
        line-height: 40px;
        color: #000;
        position: relative;
        -webkit-transition: all 0.5s;
        -moz-transition: all 0.5s;
        -o-transition: all 0.5s;
        -ms-transition: all 0.5s;
        transition: all 0.5s;
        padding: 0;
    }
    .headerTopMenu li.active a, .headerTopMenu li a:hover {
        color: #f00;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="headerTopMenu">
      <ul class="nav">
          <li class="active"><a href="#home">Home</a></li>
          <li><a href="#about">About</a></li>
          <li><a href="#service">Services</a></li>
          <li><a href="#portfolio">Portfolio</a></li>
          <li><a href="#blogs">Blog</a></li>
          <li><a href="#contact">contact</a></li>
      </ul>
    </div>

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2017-06-22
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多