2013-06-26 35 views
0
if(document.URL!="location.php?img_url="+img_url){ 
     window.location.href = "location.php?img_url="+img_url; 
    } 

這會不斷重新加載頁面。我檢查網址,看看它是否發生變化,但沒有。比較文檔時出現意外結果。網址

+2

我向你保證的JavaScript的'='操作是否正常工作! – naomik

+2

刪除了荒謬問題標題和無關標籤。 –

回答

3

!=總是正常工作。這是你誰工作錯了!

在這種情況下,問題是您期望document.URL是您設置爲window.location.href的字符串。它可能不是。

事實上,它永遠不會是"location.php?img_url="+img_url。它將始終是完整的網址,所以類似http://www.example.com/location.php?img_url="+img_url

+0

總是!正確的作品 – raam86

7

因爲看什麼document.URL是!

console.log(document.URL); 

它返回完整的url。 http://example.com/location.php?img_url=1234

您正在尋找完全匹配,而不是部分匹配。

一種解決方案是使用indexOf()

if(document.URL.toLowerCase().indexOf("location.php?img_url="+img_url)===-1){ 
0

嘗試使用

window.location.pathname 

,而不是使用

document.URL 
+1

這不包括查詢字符串。 –

2

嘗試

if(window.location != "http://www.urlhere.com/location.php?img_url="+img_url){ 
    window.location.href = "http://www.urlhere.com/location.php?img_url="+img_url; 
} 
+0

剛編輯答案。我的意思是還包括完整的URL路徑。我只知道'window.location'比'document.URL'更容易 – copilot0910

0

也許你只是忘了域名。

嘗試這樣的事:

if(document.URL!="http://localhost/location.php?img_url="+img_url){ 
    window.location.href = "http://localhost/location.php?img_url="+img_url; 
} 
1

使用document.location.pathname + document.location.search代替document.URL

+0

這不包括查詢字符串。 –

+0

@瘋狂火車感謝你 – raam86

+0

+1這應該工作。 –