簡體   English   中英

從鏈接的href屬性獲取完整的URI

[英]Get the full URI from the href property of a link

我想在某些方面得到確認。

我的目標是在從鏈接讀取href屬性時始終獲取相同的字符串(在我的情況下是URI)。 例:

使用base_url = http://domain.name/ <a href="test.htm" />

使用base_url = http://domain.name/domain/ <a href="../test.htm" />

<a href="http://domain.name/test.htm" /> base_url =來自http://domain.name/的任何文件夾

我需要從上面的3種情況(或任何其他相同的字符串)中獲取http://domain.name/test.htm

經過一些測試,似乎my_a_dom_node.href總是返回完全限定的URI,包括http://domaine.name ,這應該my_a_dom_node.href我的需要。

jQuery有不同的行為, $(my_a_dom_node).attr('href')返回HTML中出現的內容(文本)。 所以我的訣竅是使用$(my_a_dom_node).get(0).href來獲取完整的URI。

問題是:我能依靠這個嗎?

是的,你可以信賴!

有一次,當人們使用簡單的javascript(沒有jQuery)時,許多人問你要求的相反,他們想要得到href屬性中寫的真實url而不是完整的url,在這種情況下他們曾經只是這樣做:

my_a_dom_node.getAttribute('href', 2); //works both IE/FF

然后它來了jQuery,幫助人們不要浪費時間發現他們需要這樣的代碼,jQuery總是返回href屬性中寫的真實url。

有趣的是,現在有人問如何獲取完整的URL,因為jQuery返回了href屬性中寫的那個。

我知道這是一個老問題,但這實際上是第一個出現的條目,我相信添加額外的解決方案是件好事。 自從jQuery引入了“prop”功能以來,獲取完整的URL非常簡單:

$(my_a_dom_node).prop('href');

我希望這仍然有助於某人。

是的,你可以依靠這個。

通過jQuery(1.4.2)源代碼,我看到正在使用的jQuery.attr()函數(濃縮到相關部分):

jQuery.extend({
  // ...
  attr: function( elem, name, value, pass ) {
    // ...

    var attr = !jQuery.support.hrefNormalized && notxml && special ?
               // Some attributes require a special call on IE
               elem.getAttribute( name, 2 ) :
               elem.getAttribute( name );

    // Non-existent attributes return null, we normalize to undefined
    return attr === null ? undefined : attr;    
  }
});

因此它有效地調用elem.getAttribute('href') ,它返回實際的屬性值,而href屬性則通過設計返回規范的URL。

但是,有一個對jQuery.support.hrefNormalized的引用,jQuery支持站點必須說:

  • hrefNormalized :如果.getAttribute()方法檢索元素的href屬性不變,則等於true,而不是將其標准化為完全限定的URL。 (目前在IE中它是假的,URL被標准化)。 DOM l3規范

這基本上意味着jQuery自己發現瀏覽器行為並相應地調整以提供一致的結果。

您可以使用一些javascript重構完整的URL:

function parseLink(link) {
    var baseUrl = location.href.substring(0,location.href.lastIndexOf('/'));
    if (link.indexOf('/') != -1) {
        link = link.substring(link.lastIndexOf('/')); 
    } else {
        link = "/"+ link;
    }
    var fullUrl = baseUrl + link;
    return fullUrl
}

暫無
暫無

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

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