繁体   English   中英

删除#anchor之前的href链接的一部分?

[英]Remove part of the link in a href before #anchor?

我的页面上有这样一个链接:

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

我想使用jQuery删除.jump类中任何URL的' http://example.com/ '部分。 您能以最简单的代码为我指明正确的方向吗? 我希望代码在哈希之前删除所有内容,而不要在jQuery代码中指定URL(例如,删除http://example.com/ )。

谢谢!

您可以使用:

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

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

3)将新的href与前面的#连接起来,并设置新的href

$('.jump a').each(function(){
  $(this).attr('href','#'+$(this).attr('href').split('#')[1]);
});

我能想到的最简单的方法是使用锚字符#作为分隔符来拆分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上使用此功能,所以我建议您将此代码放入一个函数中,并在需要时调用。

您可以使用substringlastIndexOf

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

    $this.attr("href", href.substring(href.indexOf("#")));        
});

这是我使用jQuery的方法:

$(".jump a").each(function() {
    var newHref = $(this).attr("href").replace("http://example.com/", "");
    $(this).attr("href", newHref);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM