JQuery 检测是否在主页和主页 PLUS url 变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17271100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery Detect If in Homepage and Homepage PLUS url Variables
提问by Satch3000
I am using this code to detect the homepage and it works great:
我正在使用此代码来检测主页,并且效果很好:
var url= window.location.href;
if(url.split("/").length>3){
alert('You are in the homepage');
}
My problem is that I also need to detect if the url has variables for example:
我的问题是我还需要检测 url 是否有变量,例如:
mysite.com?variable=something
I need to also detect if the url has variables on it too
我还需要检测 url 上是否也有变量
How can I do this?
我怎样才能做到这一点?
采纳答案by Nelson
Take a look at the window.location docs, the information you want is in location.search
, so a function to check it could just be:
看看window.location docs,你想要的信息在location.search
,所以检查它的函数可能只是:
function url_has_vars() {
return location.search != "";
}
回答by Bradley Flood
Using window.location.pathname
could work too:
使用window.location.pathname
也可以:
if ( window.location.pathname == '/' ){
// Index (home) page
} else {
// Other page
console.log(window.location.pathname);
}
回答by Mataniko
You can find out if you're on the homepage by comparing href to origin:
您可以通过将 href 与 origin 进行比较来确定您是否在主页上:
window.location.origin == window.location.href
To get the query parameters you can use the answer here: How can I get query string values in JavaScript?
要获取查询参数,您可以使用此处的答案: 如何在 JavaScript 中获取查询字符串值?
回答by Sudip Pal
You need a query string searching function to do this..
您需要一个查询字符串搜索功能来执行此操作。
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Before redirect check the query string and match with the expected value and redirect as requirement.
在重定向之前检查查询字符串并与预期值匹配并根据要求重定向。
回答by benlo335
if current url is xxxxx.com something like that, then xxx
如果当前 url 是 xxxxx.com 之类的,那么 xxx
if (window.location.href.split('/').pop() === "") {
//this is home page
}