2011-07-03 52 views
1

我想檢查href屬性,如果它不包含完整路徑,我想用完整的URL替換它?我應該使用JavaScript,但不適用於IE 8?如何檢查href屬性,如果需要添加完整的url地址?

我的JS:

fullUrl = $(this).filter('[href^='+document.location.protocol+']').attr('href') 
    ? true : false; 

url = fullUrl ? 
    $(this).filter('[href^='+document.location.protocol+']').attr('href') 
    : document.location.protocol + '//' + document.domain + $(this).attr('href'); 

我需要檢查,如果HREF包含完整的URL或不:

HREF: 「/path/other.html」(部分)

href:「http://domain.com/path/other.html」(完整網址)

然後,如果我有部分網址href,我必須添加域並重新創建href到完整的URL!

+0

您的代碼不會取代'href'屬性... –

回答

3

完整的URL是通過.href屬性中可用。

通常沒有必要將其設置爲屬性,但如果你願意,你可以這樣做:

$('a[href]').attr('href', function() { return this.href; }); 

這找到了具有href屬性的所有<a>元素,並使用更新其hrefattr()[docs]方法通過傳遞一個函數作爲第二個參數,它返回.href屬性的值。


如果您只是想要一個列表,您可以使用map()[docs]方法。

var hrefs = $('a[href]').map(function() { return this.href; }).get(); 

例子:http://jsfiddle.net/EDhhD/


編輯:

如果你想明確地檢查路徑尚未完整路徑,只需添加一個if聲明我的第一個例子。

$('a[href]').attr('href', function(i,hrf) { 
    if(hrf.indexOf('http') !== 0) return this.href; 
}); 
+0

也許我的問題是不正確的!對不起:(讓我再解釋一下: – Faraona

+0

@Faraona:看看你的更新,看起來我的第一個解決方案會起作用,除了它不檢查當前的'href'。我會給你一個更新,以防你 – user113716

+0

tnx,這個工作; – Faraona

0

我想你想的:

$(this).attr('href', function(i, v) { 
    if (v.indexOf('http:') === -1) { 
     v = document.location.protocol + '//' + document.domain + '/' + v; 
    } 
    return v; 
}); 

現場演示:http://jsfiddle.net/simevidas/bwmQ5/

0

我不認爲你可以得到多個項目調用attr的有意義的結果。你應該做一次支票/替換在一個循環中,一個項目:

$(this).filter('[href^='+document.location.protocol+']').each(function(){ 
    var fullUrl = $(this).attr('href') ? true : false; 
    var url = fullUrl ? $(this).attr('href') : document.location.protocol + '//' + document.domain + $(this).attr('href'); 
    alert(url); 
}); 
0

該解決方案將確保您的網頁上的所有錨有協議在href:

$(document).ready(function() 
{ 
    var str_len = document.location.protocol.length; 
    $('a').each(function() 
    { 
     if($(this).attr('href').substring(0,str_len) != document.location.protocol) 
     { 
      $(this).attr('href',document.location.protocol + '//' + $(this).attr('href')); 
     } 
    }); 
}); 

http://jsfiddle.net/3XQXL/

相關問題