开发者

javascript location

This checks "if we are on movies.php page":

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

how to add for this (like or)开发者_StackOverflow "if we are on music.php page"?


I assume you mean you want to see if you are on movies.php or on music.php? Meaning you want to do the same thing if you are on either?

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

Or if you want to do something different, you can use an else if

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

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

Also, instead of using match you can use test:

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

Based on paulj's answer, you can refine the regular expressions in if statement that checks to see if you are on either page, to a single regular expression:

/(music|movies)\.php/


How about ..

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

Or even better...

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

Note the \., this literally matches "a single period" where as in regex . matches any character, thus these are true, but probably not what you want...

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


The following improves on previous answers in a couple ways ...

if (/(movies|music)\.php$/.test(location.pathname)) {
    var pageName = RegExp.$1; // Will be either 'music' or 'movies'
}
  • Provides the name of the page (sans .php extension) via the RegExp.$1 property
  • Using location.pathname eliminates extraneous hits on possible query parameters (e.g. "...?redirect=music.php")
  • Use of regex '|' operator combines tests into a single regex (particularly good if you have lots of pages you want to match)
  • Use of regex '$' operator constrains match to end of pathname (avoids extraneous hits in the middle of a path. Not very likely in your example, but good practice)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜