有没有烤入jQuery的方式来获得从querysting名称/值对JavaScript的变量(虽然,不应该有?)
但人们已经写纯JavaScript函数来为你做的:How can I get query string values in JavaScript?。
如果使用上述问题的第二个答案,通过Andy E,可以将所有查询字符串变量捕获到JavaScript对象的名称 - 值对。以下是他写道:
var urlParams = {};
(function() {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
然后使用这些具有相同的名称与jQuery的查询字符串的名字,像这样设置的输入表单值:
$.each(urlParams, function(key, value){
$('form [name=' + key + ']').val(value);
});
更新:,因为这是很难在jsFiddle中测试,这里是整个网页作为一个工作示例。它将用url('1','2'和'3')代替值'a','b'和'c' - 只需将它设置为test.html on localhost并转到:http://localhost/test.html?a=1&b=2&c=3
<!DOCTYPE html>
<html><head><title>Test URL params</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" >
$(function(){
var urlParams = {};
(function() {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
$.each(urlParams, function(key, value){
$('form [name=' + key + ']').val(value);
});
});
</script>
</head>
<body>
<form>
<input name="a" value ="a" /><input name="b" value ="a" /><input name="c" value ="a" />
</form>
</body></html>
感谢您的帮助。你知道这个的一个有效的例子吗?我似乎无法得到它的工作,很难在小提琴中测试? – ak85 2012-08-06 11:31:18
@ ak85:查看更新。 – Faust 2012-08-06 12:24:21