Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/479.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript window.location.href与index.php或根名称的比较_Javascript_Jquery - Fatal编程技术网

Javascript window.location.href与index.php或根名称的比较

Javascript window.location.href与index.php或根名称的比较,javascript,jquery,Javascript,Jquery,我想在需要时在JS中运行一段特定的代码 1) 该页面为mysite.com/index.php或 2) 当索引不存在时,例如mysite.com。(您可以使用apache来实现这一点) 对于1,我正在使用 1) if(/index\.php$/.test(window.location.href)){//code here} 我怎样才能做到这两个呢 2) 我试过了 if ( /http:\/\/mysite\.com/g.test(window.location.href)) { } 但这适用

我想在需要时在JS中运行一段特定的代码

1) 该页面为mysite.com/index.php或 2) 当索引不存在时,例如mysite.com。(您可以使用apache来实现这一点)

对于1,我正在使用 1)
if(/index\.php$/.test(window.location.href)){//code here}

我怎样才能做到这两个呢

2) 我试过了

if ( /http:\/\/mysite\.com/g.test(window.location.href))
{
}

但这适用于每个url(例如mysite.com/anythinghere.php)

通过比较
window.location.pathname
值,您可以更轻松地检查这一点

if (window.location.pathname == '/' || window.location.pathname == '/index.php') {
    // code here
}

如果你想知道你加载了主页,你可以试试这个

 if(/\/(index\.php)?$/.test(window.location.pathname)){
        // ...
    }
.test()
将正则表达式与字符串进行比较,因此需要转义正斜杠。您可以使用
==
来比较字符串。