2011-11-07 43 views
1

我需要查看用戶所在的當前頁面是否是網站的主頁面,即基本網址之後沒有任何內容。當前頁面是否爲基本網址?

我這樣做是爲了從主頁面中排除一些代碼。

+1

請注意,儘管在JS中可以這樣做,但如果要阻止用戶運行JS的某些部分,則不一定是個好主意。 JS運行在客戶端上,因此用戶可以完全控制它並可以根據需要進行更改。 – nico

回答

4
if (location.pathname=="/"){ 
    // at the root of the site 
} 

更多關於(跨瀏覽器)window.location對象的信息。

編輯:如果你的 '根' 由名爲index某些文件可能擔任(如index.htmlindex.phpindex.asp等),你可能想:

var rootPattern = /^\/(?:index\.[^.\/]+)?$/i; 
if (rootPattern.test(location.pathname)){ 
    // … 
} 

或更明確:

switch(location.pathname){ 
    case '/': 
    case '/index.html': 
    case '/index.php': 
    case '/index.asp': 
    // … 
} 
相關問題