2010-06-14 14 views
1

此檢查, 「如果我們在movies.php頁」:JavaScript位置

if (location.href.match(/movies.php/)) { 
// something happens 
} 

如何添加此(如or) 「如果我們在music.php頁」?

回答

1

我假定你的意思是你想看看你是否在movies.phpmusic.php?意思是你想做同樣的事情,如果你在任何一方?

if (location.href.match(/movies\.php/) || location.href.match(/music\.php/)) { 
// something happens 
} 

或者,如果你想要做不同的東西,你可以用一個else if

if (location.href.match(/movies\.php/)) { 
// something happens 
} 

else if(location.href.match(/music\.php/)) { 
// something else happens 
} 

而且,而是採用match您可以使用test:基於paulj的回答

if (/movies\.php/.test(location.href) || /music\.php/.test(location.href)) { 
// something happens 
} 

,您可以細化if語句中的正則表達式,該語句用於檢查您是否位於任一頁上,以檢查單個常規表情:

/(music|movies)\.php/ 
1

如何..

if (/(movies\.php|music\.php)/.test(location.href)) { 
// Do something 
} 

甚至更​​好...

if (/(movies|music)\.php/).test(location.href)) { 
// Do something 
} 

注意\,這從字面上匹配 「一個週期」,其中在正則表達式。匹配任何字符,因此這些都是真實的,但可能不是你想要的...

if (/movies.php/.test('movies_php')) alert(0); 
if (/movies.php/.test('movies/php')) alert(0); 
0

下在幾個方面以前的答案改善...

if (/(movies|music)\.php$/.test(location.pathname)) { 
    var pageName = RegExp.$1; // Will be either 'music' or 'movies' 
} 
  • 提供名稱通過RegExp。$ 1屬性
  • 使用location.pathname消除了對可能的查詢參數(例如「...?redirect = music.php」)的無關命中
  • 使用re gex'|'運算符將測試合併到一個正則表達式中(尤其是如果你有很多頁面需要匹配的話)
  • 使用正則表達式'$'操作符限制匹配到路徑名的結尾(避免在路徑中間多餘的點擊。可能在你的例子中,但良好的做法)