2014-09-23 51 views
0

我想用jQuery替換所有HTTP到頁面的HTTPS。Repalce所有HTTP到HTTPS的頁面

我想這一點:

jQuery('a').each(function() { 
    var href = jQuery(this).attr('href'); 
    if (href.indexOf('http:') > -1) { 
     href = href.replace('http:', 'https:'); 
     jQuery(this).attr('href', href); 
    } 
}); 

我想替換HTTP:爲https:在頁面加載 指導我如何做到這一點?

+1

我沒有看到任何錯誤。你是什​​麼意思不起作用?控制檯錯誤? – laaposto 2014-09-23 13:03:03

+1

你把代碼放在'$(document).ready()'函數中嗎? – Jerodev 2014-09-23 13:03:35

+0

它不會將http替換爲https – 2014-09-23 13:09:08

回答

4

您可以設置屬性:

$("a[href]").each(function(){ 
    if(this.protocol === "http:") 
     this.protocol = "https:" 
}); 
+2

有+1用於教我新的東西。謝謝 :) – Archer 2014-09-23 13:18:16

1

使用jQuery的attr不會得到完整的URL,但輸入的內容是href值,它可能只是一個本地路徑。試試這個...

jQuery('a').each(function() { 
    this.href = this.href.replace("http:", "https:"); 
}); 

使用this.href將讓你絕對URL代替,所以它總是與協議類型爲前綴。