JQuery检测如果在主页和主页PLUS url变量

Sat*_*000 22 javascript url jquery pathname

我正在使用此代码来检测主页,它运行良好:

var url= window.location.href;
if(url.split("/").length>3){
    alert('You are in the homepage');
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我还需要检测url是否有变量,例如:

mysite.com?variable=something
Run Code Online (Sandbox Code Playgroud)

我还需要检测url是否也有变量

我怎样才能做到这一点?

Bra*_*ood 61

使用window.location.pathname也可以工作:

if ( window.location.pathname == '/' ){
    // Index (home) page

} else {
    // Other page
    console.log(window.location.pathname);
}
Run Code Online (Sandbox Code Playgroud)

请参阅window.location.pathname上的MDN信息.

  • `如果(window.location.pathname == '/' || window.location.pathname == '的index.php'){//你的东西}` (2认同)

Mat*_*iko 11

你可以通过比较href和origin来了解你是否在主页上:

window.location.origin == window.location.href
Run Code Online (Sandbox Code Playgroud)

要获取查询参数,您可以在此处使用答案: 如何在JavaScript中获取查询字符串值?

  • 我注意到href可以返回带有斜杠的url,例如mysite.com/,而原点没有斜线... (4认同)

Nel*_*son 6

看一下window.location文档,你想要的信息location.search,所以检查它的函数可能只是:

function url_has_vars() {
   return location.search != "";
}
Run Code Online (Sandbox Code Playgroud)