0

我在 Wordpress 中有一个使用 WP Menu 系统的菜单。所有链接基本上都是自定义链接,输出以下内容(为简洁起见,删除了 WP 类):

<ul>
<li><a href="http://mysite.com/about">About</a>
 <ul>
   <li><a href="http://mysite.com/about/#section-1">Section 1</a></li>
   <li><a href="http://mysite.com/about/#section-2">Section 2</a></li>
   <li><a href="http://mysite.com/about/#section-3">Section 3</a></li>
  </ul>
 </li>

<li><a href="http://mysite.com/services">Services</a>
 <ul>
   <li><a href="http://mysite.com/services/#section-1">Section 1</a></li>
   <li><a href="http://mysite.com/services/#section-2">Section 2</a></li>
   <li><a href="http://mysite.com/services/#section-3">Section 3</a></li>
   <li><a href="http://mysite.com/services/#section-4">Section 4</a></li>
  </ul>
 </li>
</ul>

如果正在查看父页面,我正在尝试删除 URL 的域部分,因此如果我正在查看“关于”页面,菜单中的链接将更改为:

<li><a href="http://mysite.com/about">About</a>
 <ul>
   <li><a href="#section-1">Section 1</a></li>
   <li><a href="#section-2">Section 2</a></li>
   <li><a href="#section-3">Section 3</a></li>
  </ul>
</li>

<li><a href="http://mysite.com/services">Services</a>
 <ul>
   <li><a href="http://mysite.com/services/#section-1">Section 1</a></li>
   <li><a href="http://mysite.com/services/#section-2">Section 2</a></li>
   <li><a href="http://mysite.com/services/#section-3">Section 3</a></li>
   <li><a href="http://mysite.com/services/#section-4">Section 4</a></li>
  </ul>
 </li>

</ul>

jQuery 的问题是我无法定位每个特定页面,因为这些页面是未知的,因此我需要它来获取 URL 并将其与菜单的正确部分匹配以更改链接。我已经尝试过了,但它太具体了:

if (window.location.href.indexOf("about") != -1) {

  //do something

} else {

  //do something else

}

编辑

我只想更改当前页面菜单中的链接。到目前为止的答案改变了菜单中的所有链接,我只想定位在同一页面上找到的链接。

4

3 回答 3

3

演示在这里

首先向元素添加一个类sectionsul使其易于定位。

<ul class="sections">
    <li><a href="http://mysite.com/about/#section-1">Section 1</a>
    </li>
    <li><a href="http://mysite.com/about/#section-2">Section 2</a>
    </li>
    <li><a href="http://mysite.com/about/#section-3">Section 3</a>
    </li>
</ul>

用于.map()更换href每个锚点。

编辑 - 基于您的新更新,我也喜欢 @Archer 的更新。这应该有效。

$(".sections a[href* = '" + window.location.pathname + "/#']").map(function(){
    var currentsection = this.href.split('/').pop();
    this.href = currentsection;
});
于 2013-11-07T16:07:45.630 回答
2

另外的选择...

$(function() {
    $("a[href*='" + window.location.pathname + "#']").attr("href", function() {
        return "#" + this.href.split("#")[1];
    });
});

这将找到当前页面的所有链接以及其中的 a#并相应地修复 href 值。

于 2013-11-07T16:07:53.500 回答
0

尝试这个,

$('a').each(function(){
   // check the anchor tab href has location.href or not
   if($(this).attr('href').indexOf(window.location.href) != -1)
   {
       // some code to replace location.href to blank
       var href=$(this).attr('href').replace(window.location.href,'');
       $(this).attr('href',href);
   }
});

或者,试试这个,

$('a').each(function(){
   if(this.href.indexOf('#') != -1)
   {
       var href=this.href.split('#')[1];
       this.href = '#'+href;
   }
});
于 2013-11-07T16:04:30.677 回答