【问题标题】:Menu active state remain on clicked link after the page reload页面重新加载后,菜单活动状态保持在单击的链接上
【发布时间】:2015-10-29 15:54:59
【问题描述】:

我的菜单有问题。我希望活动状态保持在最后点击的链接上。

<ul id="nav">
    <li class="active"><a href="?field1="2"&field2="test">products </a></li>
    <li><a href="?field1="3"&field2="test2">products2 </a></li>
</ul>

当我单击 products2 时,右侧的表格将根据 url 中的字段填充数据库,这将刷新页面。我怎样才能让点击的链接保持活动类?

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    以下应该可以工作:

    var qs = decodeURIComponent(location.search);
    $('a[href="' + qs + '"]').parents('li').addClass('active');
    

    location.search 中,您将找到附加到您的 URL 的查询字符串。

    decodeURIComponent 将解码您的 URL,从而避免例如%20 表示空格。

    $('a[href="' + qs + '"]') 选择 a 标记,该标记具有与您的查询字符串相对应的 href 属性。

    但我建议从href 中的 url 参数中删除额外的 "

    <ul id="nav">
        <li class="active"><a href="?field1=2&field2=test">products </a></li>
        <li><a href="?field1=3&field2=test2">products2 </a></li>
    </ul>
    

    如果您无法删除引号,则必须将它们转义才能使属性选择器起作用。


    参考

    location.search

    decodeURIComponent

    jQuery attribute selector

    .parents()

    .addClass()

    【讨论】:

      【解决方案2】:

      您可以检查 url,然后将类应用于相关元素。这可以在服务器端或客户端完成(我看到你用客户端技术标记了它)

      这样

      //if url contains "field1=3" then add the class "selected" to element "tab2"
      if (window.location.href.indexOf("field1=3") > -1) {
         $("#tab2").addClass("selected")
      }
      

      值和选项卡显然应该以某种方式进行结构化,但你明白了要点。

      【讨论】:

      • 你能解释更多吗?对不起,我对这个完全是菜鸟。而且我不使用标签,我只想要链接。
      【解决方案3】:

      使用 jQuery,您可以在您的场景中尝试这个。

         var currentPath="?"+window.location.href.split("?")[1];
         $("a[href='"+currentPath+"']").parent().addClass("active");
      

      【讨论】:

        【解决方案4】:

        简单但丑陋的解决方案是在product2页面上添加代码以手动突出显示链接。

        或者,如果问题出在所有链接上,并且将来会有 n 个链接可用,那么您的代码应该更加结构化。在这种情况下,您可以将处理此类常见工作的通用代码(突出显示侧栏上的链接)放在一个通用 js 文件中。而不是放在所有页面上。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-23
          • 2015-12-17
          • 2021-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-18
          相关资源
          最近更新 更多