此檢查, 「如果我們在movies.php
頁」:JavaScript位置
if (location.href.match(/movies.php/)) {
// something happens
}
如何添加此(如or
) 「如果我們在music.php
頁」?
此檢查, 「如果我們在movies.php
頁」:JavaScript位置
if (location.href.match(/movies.php/)) {
// something happens
}
如何添加此(如or
) 「如果我們在music.php
頁」?
我假定你的意思是你想看看你是否在movies.php
或music.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/
如何..
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);
下在幾個方面以前的答案改善...
if (/(movies|music)\.php$/.test(location.pathname)) {
var pageName = RegExp.$1; // Will be either 'music' or 'movies'
}