不废话,just show code,注释已经很详尽。
www根目录下新建demo文件夹,复制代码到demo文件夹并命名为year.html,同目录下放jquery.min.js。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.min.js"></script>
</head>
<body>
<div>
<select id="select">
<option>year chooise</option>
</select>
</div>
<script>
//获取url关键字
function getQueryVariable(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
var r = window.location.search.substr(1).match(reg);
var q = window.location.pathname.substr(1).match(reg_rewrite);
if(r != null){
return unescape(r[2]);
}else if(q != null){
return unescape(q[2]);
}else{
return null;
}
}
//如果获取到year,那么year为获取到的,否则为当前年份减1年(减1为统计之前一年年报)
if (getQueryVariable("year")) {
var year = getQueryVariable("year");
} else {
var year = new Date().getFullYear()-1;
}
console.log(year);
//select 调后台接口
$("#select").change(function(){
window.location.href = 'http://localhost/demo/year.html?year=' + $("#select").val();
console.log($(this).val());
});
//ownerTimeAll为伪造数据,本来是接口获取到的用户最早使用到去年的数组
var ownerTimeAll = [2014,2015,2016,2017];
//构造select
for (var i = ownerTimeAll[0]; i<= ownerTimeAll[ownerTimeAll.length - 1]; i++) {
$("#select").append("<option value='"+i+"' >"+i+"</option>");
}
//1.设置Select的Value值为year的项选中 1,2,3皆可
$("#select").val(year);
//2.设置Select索引值为1的项选中
// $("#select ").get(0).selectedIndex=1;
//3.设置Select的value值为2016的项选中
// $("#select option[value='2016']").attr("selected", true);
</script>
</body>
</html>
原URL关键字在传base64加密遇到"="会找不到参数,已将原文替换新URL关键字查询
第一种方法
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
第二种更好的方法
//URL关键字
function getQueryVariable(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
var r = window.location.search.substr(1).match(reg);
var q = window.location.pathname.substr(1).match(reg_rewrite);
if(r != null){
return unescape(r[2]);
}else if(q != null){
return unescape(q[2]);
}else{
return null;
}
}
网友评论