使用esc_url将{Active'类应用于当前页面菜单项

时间:2016-10-29 19:52:13

标签: wordpress menu zurb-foundation

我正在尝试将一类'active'应用于当前页面的相应菜单项。我从来没有遇到过这个问题/花了几个小时阅读类似的问题无济于事我认为这与使用Wordpress的esc_url我的菜单链接有关,但我无法弄清楚为什么这不起作用...我的jQuery似乎无法匹配网址。当我在Page1上时,我想将一个活动类应用于相应的li,依此类推。这是一个多页的网站。有任何想法吗?我正在使用FoundationPress,一个用于Foundation的Wordpress样板文件。

<div class="top-bar" id="main-menu">
  <div class="mobile-bar mobile">
    <ul class="menu vertical dropdown text-center" data-dropdown-menu>
      <li><a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a></li>
      <li><a href="<?php echo esc_url( home_url( '/Page1' ) ); ?>">Page 1</a></li>
      <li><a href="<?php echo esc_url( home_url( '/Page2' ) ); ?>">Page 2</a></li>
      <li><a href="<?php echo esc_url( home_url( '/Page3' ) ); ?>">Page 3</a></li>
      <li><a href="<?php echo esc_url( home_url( '/Page4' ) ); ?>">Page 4</a></li>
    </ul>
  </div>
</div>

<style>
.menu > li {
display: inline-block;
padding:0 1em;
}
</style>

<script>
$(document).foundation();

var href = location.href;
 var pgurl = href.substr(href.lastIndexOf('/') + 1);
   // match all the anchors on the page with the html file name
   $('.menu a[href="' + pgurl + '"]').addClass('active');
</script>

1 个答案:

答案 0 :(得分:0)

最终可以使用这段代码找到答案:

var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
    // now grab every link from the navigation
    $('.menu a').each(function(){
        // and test its normalized href against the url pathname regexp
        if(urlRegExp.test(this.href.replace(/\/$/,''))){
            $(this).addClass('active');
        }
});

链接到解决这个问题的原始海报 - 请向他投票! link

相关问题