4

我的页面上有一个链接:

<li class="jump"><a href="http://example.com/#about">About Me</a></li>

我想使用 jQuery 删除 .jump 类中任何 URL 的“ http://example.com/ ”部分。你能用最简单的代码指出我正确的方向吗?如果可能,我希望代码在散列之前删除任何内容,而不是在 jQuery 代码中指定 URL(例如删除http://example.com/ )。

谢谢你!

4

4 回答 4

6

您可以使用:

1).each()遍历所有锚点

#2)在出现并使用第二个数组元素时拆分当前href

3)将新href与#前面连接并设置新href

$('.jump a').each(function(){
  $(this).attr('href','#'+$(this).attr('href').split('#')[1]);
});
于 2015-03-10T12:27:35.743 回答
0

这是我使用 jQuery 的方法:

$(".jump a").each(function() {
    var newHref = $(this).attr("href").replace("http://example.com/", "");
    $(this).attr("href", newHref);
});
于 2015-03-10T12:40:54.383 回答
0

我能想到的最简单的方法是使用锚字符#作为分隔符来拆分 URL:

var url = $(".jump").attr("href"); // "http://example.com/#about"
var split_url = url.split("#");
var after_hash = split_url[1];

您的after_hash变量现在应该包含值:“about”。如果您打算将锚字符重新插入到href属性中,则需要将锚字符重新添加到该值中。

由于在我看来您打算在多个 url 上使用此功能,因此我建议将此代码放入函数中并在需要时调用。

于 2015-03-10T12:26:31.697 回答
0

您可以使用substringlastIndexOf

$(".jump a").each(function() {    
    var $this = $(this),
        href = $this.attr("href");

    $this.attr("href", href.substring(href.indexOf("#")));        
});
于 2015-03-10T12:28:11.193 回答