2012-08-27 42 views
3

如果用戶訪問我的網站的根網址,我想運行一個js腳本。我使用此代碼:檢查用戶是否訪問純根URL

<script type="text/javascript"> 
    if(location.pathname == "/") { 
     window.open ('#107','_self',false); 
    } 
</script> 

然而http://example.com/?foo=bar#hash也將運行腳本,因爲路徑不包括查詢字符串和位置哈希值。

目前,它的行爲是這樣的:

http://example/     Root 
       /?querystring  Root 
       /#hash    Root 
       /page    Not root 

我希望它這樣的表現:

http://example/     Root 
       /?querystring  Not root 
       /#hash    Not root 
       /page    Not root 

有什麼建議? 謝謝。

+0

我需要你相反的情況下使你的代碼,因爲它是一個沒有修復是我正好經過,謝謝:) –

回答

4

使用window.location.href代替

+0

這一工程!很簡單,我很尷尬。謝謝。 –

+1

我編輯我的代碼以下和它的工作: '<腳本類型= 「文本/ JavaScript的」> \t如果(window.location.href == 「http://example.com/」){ \t \t window.open('#107','_ self',false); \t} ' –

2

您可以連接的路徑,location.search和的location.hash。

var fullPath = location.pathname + location.search + location.hash; 
if(fullPath == "/") { /* whatever */ } 
2

您可以測試所有三個組成部分:

<script type="text/javascript"> 
    if(location.pathname == "/" && 
     location.hash.length <= 1 && 
     location.search.length <= 1) { 
     window.open ('#107','_self',false); 
    } 
</script>