2010-06-14 60 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'|'运算符将测试合并到一个正则表达式中(尤其是如果你有很多页面需要匹配的话)
  • 使用正则表达式'$'操作符限制匹配到路径名的结尾(避免在路径中间多余的点击。可能在你的例子中,但良好的做法)