我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
当前回答
对Sameer的回答略有改进,将参数缓存为闭包,以避免每次调用时解析和遍历所有参数
var getURLParam = (function() {
var paramStr = decodeURIComponent(window.location.search).substring(1);
var paramSegs = paramStr.split('&');
var params = [];
for(var i = 0; i < paramSegs.length; i++) {
var paramSeg = paramSegs[i].split('=');
params[paramSeg[0]] = paramSeg[1];
}
console.log(params);
return function(key) {
return params[key];
}
})();
其他回答
这可能有点过分了,但是现在有一个非常流行的用于解析uri的库,叫做URI.js。
例子
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow"; var components = URI.parse(uri); var query = URI.parseQuery(components['query']); document.getElementById("result").innerHTML = "URI = " + uri; document.getElementById("result").innerHTML += "<br>technology = " + query['technology']; // If you look in your console, you will see that this library generates a JS array for multi-valued queries! console.log(query['technology']); console.log(query['blog']); <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script> <span id="result"></span>
2023年起的解决方案
我们有:http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
sent存在吗?
searchParams.has('sent') // true
它等于"是"吗?
let param = searchParams.get('sent')
然后比较一下。
使用这个
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
还有另一种功能……
function param(name) {
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
Sameer回答的咖啡脚本版本
getUrlParameter = (sParam) ->
sPageURL = window.location.search.substring(1)
sURLVariables = sPageURL.split('&')
i = 0
while i < sURLVariables.length
sParameterName = sURLVariables[i].split('=')
if sParameterName[0] == sParam
return sParameterName[1]
i++