【问题标题】:Ho to make current menu active on query page?如何在查询页面上激活当前菜单?
【发布时间】:2014-05-17 15:10:44
【问题描述】:

好的,我使用此脚本更改菜单样式以突出显示当前页面。我将此脚本放在我的页眉中,并将 php require_once 放在其他页面的页眉中。

<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function(){
  $('a').each(function() {
    if ($(this).prop('href') == window.location.href) {
      $(this).addClass('current');
    }
  });
});
</script>

我在我的 styles.css 中设置了 .current 类。

所以一切都很好,可以突出显示当前页面菜单。

唯一的问题是,当我在当前页面中点击排序或过滤数据库等查询时,此脚本不起作用。我认为这是因为动态地址如/page.php 更改为/page.php?hjggj=hbhj 等...

我需要解决这个问题。请注意,我不会使用 html 和 css 将类分配给当前页面方法。

提前谢谢你!

【问题讨论】:

    标签: javascript php jquery html css


    【解决方案1】:

    将您的功能更改为:

    if ($(this).prop('href') == window.location.href.replace(/\?.*/,"")) {
          $(this).addClass('current');
    }
    

    完整代码:

    $(function(){
      $('a').each(function() {
        if ($(this).attr('href') == window.location.href.replace(/\?.*/,"")) {
            $(this).addClass('current');
        }
      });
    });
    

    我想你是在比较:

    "/page.php" == "/page.php?ewrfwefwef"
    

    返回false。所以我正在做的是剥离每个查询字符串。

    【讨论】:

    • 谢谢,但这会导致代码错误。还是我错过了什么?
    • @user3500464,是的,我错过了)。现在看看
    • 再次感谢您。但是您的代码再次产生错误。
    • 谢谢,但它不起作用,另外,这次没有当前页面突出显示。
    • @user3500464,你能告诉我你的hrefhref 是什么样的吗?
    【解决方案2】:

    定位无序列表菜单时: 在文档就绪时启动它:

    $(document).ready(function(){
        $('a[href="'+window.location.pathname.split('/').pop()+'"]').parent('li').addClass('current');
    });
    

    适用的示例菜单:

    <ul class="nav">
    <li><a href="index.php">Index</a></li>
    <li><a href="service.php">Service</a></li>
    <li><a href="portfolio.php">Portfolio</a></li>
    </ul>
    

    【讨论】:

    • 我确定我的菜单与您显示的完全一样,但代码在我的页面中不起作用。也许是因为我 require_once 标题在这种情况下变得复杂?
    【解决方案3】:

    试试这个

    $('#nav a').each(function(index) {
    $navA = this.href.split('/')[4].split('?')[0];
    $winA = String(window.location).split('/')[4].split('?')[0];
    if($navA == $winA){
        $(this).addClass('current');
    }
    

    【讨论】:

      【解决方案4】:

      试试下面的代码:

      function parseUrl( url ) {
          var a = document.createElement('a');
          a.href = url;
          a.search = '';
          return a;
      }
      var currentLocation=parseUrl(window.location.href);
      $(function(){
          $('a').each(function() {
              if (this.href == currentLocation.href) {
                  $(this).addClass('current');
              }
          });
      });
      

      【讨论】:

      • 你能分享你的实际html吗?使用我的代码是否显示任何错误?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多