簡體   English   中英

jQuery替換相對鏈接

[英]jQuery replacing relative links

希望有人可以解釋我在jQuery中遇到的一些奇怪的行為。 以下腳本正在我的頁面上查找相關鏈接並用絕對鏈接替換它們。

$(document).ready(function() {
  $("a[href^='/']").each(function(){ 
    var cur_href = $(this).prop("href");
    $(this).prop("href", 'http://www.mysite.com'+cur_href);
  });
});

我在一個將通過https提供的頁面上使用此腳本,但我不希望所有導航都鏈接到https頁面。 由於我的導航是全局包含的,這似乎是解決問題的最簡單方法。

我遇到的問題出現在實際更換中。 腳本的第二行正確匹配頁面上的所有相對鏈接,然后運行腳本的替換部分。 這是替換,第4行,我得到一些奇怪的結果。 在腳本的這部分運行后,我的URL最終看起來像這樣:

HTTP://www.mysite.comhttps//www.mysite.com/mypage.htm

顯然沒有做我想做的事。 看起來腳本的第一部分與相對URL匹配,但是當替換部件觸發時,瀏覽器已經添加了域信息。

到目前為止,我發現的唯一實際上就是我想做的就是編寫替代品,預測瀏覽器的內容:

this.href = this.href.replace(/^https:\/\/www\.mysite\.com\//, "http://www.mysite.com/");

有一個更好的方法嗎?


編輯: 這是一個問題的解決方案

jQuery在這里沒有引起問題。 問題是, 根據規范 ,HTMLAnchorElement的href屬性(對象jQuery返回的類型)始終包含絕對URI。

在HTML5中, href一個復合屬性 ,你可以通過修改href.protocolhref.protocol交換協議( //之前的部分),例如:

var link = $( '<a href="https://example.com/foo">bar</a>' )[0];
console.log( link.href );
// => https://example.com/foo

link.href.protocol = 'http:';
console.log( link.href );
// => http://example.com/foo

對於沒有復合href舊瀏覽器,您只需要使用正則表達式:

console.log( link.href );
// => https://example.com/foo

link.href = link.href.replace( /^https:/, 'http:' );
console.log( link.href );
// => http://example.com/foo

TLDR:您的代碼應如下所示:

$( "a[href^='/']" ).prop( "href",
  function( _idx, oldHref ) {
    return oldHref.replace( /^https:/, 'http:' );
  }
);

PS你會注意到我$.each你的$.each電話。 這是因為prop自動匹配的集合中的每個元素的作用,也就是說,它已經這樣做你在做什么, each


.prop(propertyName,function(index,oldPropertyValue))

  • propertyName要設置的propertyName的名稱。
  • function(index, oldPropertyValue)將值返回到set的函數。 接收set中元素的索引位置和舊屬性值作為參數。 在函數內,關鍵字this指的是當前元素。

代碼:

$(function() {
    $('input').click(function() {
        $('a').not('[href^="http"],[href^="https"],[href^="mailto:"],[href^="#"]').each(function() {
            $(this).attr('href', function(index, value) {
                if (value.substr(0,1) !== "/") {
                    value = window.location.pathname + value;
                }
                return "http://mynewurl.com" + value;
            });
        });
    });
});

看到這個jsfiddle: http//jsfiddle.net/aknosis/kWrjr/

以下是我解決此問題的鏈接: http//aknosis.com/2011/07/17/using-jquery-to-rewrite-relative-urls-to-absolute-urls-revisited/

這不是很好,但它應該適用於各種瀏覽器:

$(document).ready(function() {
  $("a[href^='/']").each(function(){ 
    var cur_href = $(this).attr("href");
    if( cur_href.indexOf( "http" ) !== -1 ) {
        $(this).attr("href", cur_href);
    } else {
        $(this).attr("href", 'http://www.mysite.com'+cur_href);
    }  
  });
});

嘗試這樣的事情:

if(! /http/.test( cur_href) ){
   $(this).attr("href", 'http://www.mysite.com'+cur_href);

}

.prop()獲取屬性值而不是屬性值。 雖然相似,但有一些微妙的,重要的差異 - 其中一個適用於此。 元素上的href屬性始終是完整路徑。 例如:

<a id="myAnchor" href="/foo.html"></a>

<script>
elem = document.getElementById('myAnchor');
$elem = $(elem);
alert(elem.href); //alerts the full path, http://www.example.com/foo.html
alert($elem.prop('href')); //same as above
alert($elem.attr('href')); //alerts just "/foo.html"
</script>

換句話說,您將域附加到已經是絕對路徑的值。 只需使用.attr()而不是.prop() ,你就可以了。

要查看示例,請打開控制台並轉到此頁面: http//jsfiddle.net/JUcHU/

試着簡單地用

$(document).ready(function() {
  $("a[href^='/']").each(function(){ 
    var cur_href = this.href;  /* <-- access to the href attribute 
                                      through the DOM reference */  
    $(this).prop("href", 'http://www.mysite.com'+cur_href);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM