有沒有烤入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