简体   繁体   English

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

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

I have a link on my page as so: 我的页面上有这样一个链接:

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

I'd like to use jQuery to remove the ' http://example.com/ ' part of any URL within a .jump class. 我想使用jQuery删除.jump类中任何URL的' http://example.com/ '部分。 Can you point me in the correct direction, with the simplest code possible? 您能以最简单的代码为我指明正确的方向吗? I want the code to remove anything before the hash, without specifying the URL (eg remove http://example.com/ ) in the jQuery code if possible. 我希望代码在哈希之前删除所有内容,而不要在jQuery代码中指定URL(例如,删除http://example.com/ )。

thank you! 谢谢!

You can use: 您可以使用:

1) .each() to iterate over the all anchor 1) .each()遍历所有锚点

2) split current href on occurence of # and use second array element 2)在出现#拆分当前href,并使用第二个数组元素

3) concatenate the new href with # in front and set the new href 3)将新的href与前面的#连接起来,并设置新的href

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

The simplest method I can think of would be to split the URL using the anchor character # as the delimiter: 我能想到的最简单的方法是使用锚字符#作为分隔符来拆分URL:

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

Your after_hash variable should now contain the value: "about". 您的after_hash变量现在应包含值:“ about”。 You'll need to re-add the anchor character to this value if you intend to insert it back into the href attribute. 如果打算将锚字符重新插入到href属性中,则需要将锚字符重新添加到该值。

Since it sounds to me like you are intending to use this functionality on multiple urls, I would recommend placing this code into a function and calling when needed. 由于对我来说听起来像您打算在多个URL上使用此功能,所以我建议您将此代码放入一个函数中,并在需要时调用。

You could use substring and lastIndexOf . 您可以使用substringlastIndexOf

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

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

Here is how I would do it using jQuery: 这是我使用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