簡體   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