把URL参数解析为一个对象

<!DOCTYPE html>      
<html lang="en">      
<head>      
    <meta charset="UTF-8">      
    <title>把URL参数解析为一个对象</title>    
    <style type="text/css">
    </style>     
</head>      
<body>
	<script type="text/javascript">
		function parseQueryString(url) {
		   var params = {};
		   var arr = url.split("?");
		   if (arr.length <= 1) {
		      return params;
		   }
		   arr = arr[1].split("&");
		   for(var i = 0, l = arr.length; i < l; i++) {
		      var a = arr[i].split("=");
		      params[a[0]] = a[1];
		   }
		   return params;
		}

		var url = "http://www.baidu.com?key0=0&key1=1&key2=2";
		var ps = parseQueryString(url);
		console.log(ps["key0"]);  //0
		console.log(ps["key1"]);  //1
		console.log(ps["key2"]);  //2
	</script>
</body>      
</html> 
相关文章
相关标签/搜索