2010-12-02 69 views
4

我想知道如何讓JavaScript來檢查用戶是否在某個URL上,以便我可以從結果中構建if語句。JavaScript當前URL檢查

我的推理是,如果用戶點擊菜單中的鏈接,他們目前在trucks.php JavaScript將重定向到某個頁面。如果他們不在卡車.php上,他們將被導向到不同的頁面。

乾杯傢伙。

回答

9

當前位置在location.href

位置對象還包含一些其他有用的字段:

  • 的location.hash:主機名包括端口(如果指定)
  • 的位置:#在URL
  • location.host後的部分.hostname:只是主機名
  • location.pathname:所請求的URI,不帶協議/主機/端口;開始與/
  • location.port:端口 - 僅當在URL
  • location.protocol指定一個:一般的 'http:' 或 'https:' - 介意結腸末

在你的情況下,最失敗的,安全的方式來檢查文件名是trucks.php是這樣的:

var parts = location.pathname.split('/'); 
if(parts[parts.length - 1] == 'trucks.php') { 
    location.href = 'some-other-page'; 
} 

如果不想保留當前頁面的歷史重定向,使用下面的代碼,而不是location.href作業:

location.replace('some-other-page'); 
+0

乾杯。 – 2010-12-02 15:24:52

4

使用window.location.href獲取當前URL或window.location.pathname以獲取路徑。爲了您的具體問題,需要解決人的路名:

if (window.location.pathname == "/trucks.php") 
    window.location = "/somewhereelse.php"; 

退房的MDC documentation for window.location

+1

嘖嘖這麼簡單。謝了哥們。 – 2010-12-02 15:24:33

0

使用window.location的