检查是否使用 JQuery 设置了 URL 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6001839/
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
Check whether a URL variable is set using JQuery
提问by Stanley Ngumo
I would like to know whether there is a jQuery function which can check whether a variable in the URL is set.
我想知道是否有一个jQuery函数可以检查是否设置了URL中的变量。
Something similar to the isset() function in PHP
类似于 PHP 中的isset() 函数
Thanks
谢谢
回答by Erick Petrucelli
jQuery doesn't have native functions to get URL parameters.
jQuery 没有获取 URL 参数的本机函数。
But you can write your own plugin to it:
但是您可以为它编写自己的插件:
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
Then you can do anything like it:
然后你可以做任何类似的事情:
if ($.getUrlVar("MyParam") != null) {
// Do anything...
}
回答by Gumbo
jQuery does not provide such methods. But you don't even need jQuery to do so:
jQuery 不提供此类方法。但你甚至不需要 jQuery 来做到这一点:
(function() {
var params = null;
this.l = typeof Location !== "undefined" ? Location.prototype : window.location;
this.l.getParameter = function(name) {
return Array.prototype.slice.apply(this.getParameterValues(name))[0];
};
this.l.getParameterMap = function() {
if (params === null) {
params = {};
this.search.substr(1).split("&").map(function(param) {
if (param.length === 0) return;
var parts = param.split("=", 2).map(decodeURIComponent);
if (!params.hasOwnProperty(parts[0])) params[parts[0]] = [];
params[parts[0]].push(parts.length == 2 ? parts[1] : null);
});
}
return params;
};
this.l.getParameterNames = function() {
var map = this.getParameterMap(), names = [];
for (var name in map) {
if (map.hasOwnProperty(name)) names.push(name);
}
return names;
};
this.l.getParameterValues = function(name) {
return this.getParameterMap()[name];
};
})();
This extends the location
object with the methods getParameter
, getParameterMap
, getParameterNames
, and getParameterValues
(similar to Java's ServeletRequest) that can be used as follows:
这location
使用方法getParameter
、getParameterMap
、getParameterNames
和getParameterValues
(类似于Java 的ServeletRequest)扩展了对象,可以按如下方式使用:
if (typeof location.getParameter("foo") !== "undefined") {
// foo parameter exists
}
The return values of getParameter
have the following meaning:
的返回值getParameter
具有以下含义:
undefined
: given parameter not presentnull
: given parameter has no assigned value (e.g.foo
ina=b&foo&c=d
)- any string value otherwise.
undefined
: 给定参数不存在null
: 给定参数没有赋值(例如foo
ina=b&foo&c=d
)- 否则为任何字符串值。