由于项目需求,需要自定制年月日上午这种四级联动,经过模仿官方weui.min.js实现了上述功能。
根据此种样式可以灵活实现月日两级联动或年月日 时分秒 六级联动功能。代码如下:
<link rel="stylesheet" href="/wxweb/css/weui.css"> //注意改为自己的路径
<script src="/wxweb/static/wxweb/jquery/jquery-3.4.1.min.js"></script>
<body><input type="text" id="test"/></body>
<script src="/wxweb/js/weui/weui.min.js"></script>
<script src="/wxweb/static/wxweb/js/test.js"></script>
test.js如下:
$(document).ready(function() {$('#test').on('click', function() {weui.picker(setmydate(), {//此处编写各种属性和事件onConfirm: function(result) {console.log(result);}});});
});
function setmydate() {var t = new Date;var year = [];if(!year.length){for(var i = t.getFullYear() - 5; i < t.getFullYear() + 5; i++){year.push({label: i+'年',value: i,});}}var month = [];if(!month.length) {for(var i = 1; i < 13; i++) {month.push({label: i + "月" ,value: i});}}var day = [];if(!day.length){for(var i = 1; i < 32; i++) {day.push({label: i + "日" ,value: i});}}var halfday = [{label:'上午',value:'1'},{label:'下午',value:'2'}]var mydate_select = [];//根据相关数据源进行绑定$.each(year, function(i) {var level1 = {label: year[i].label,value: year[i].value,children: []};$.each(month, function(j) {if(1) {var level2 = {label: month[j].label,value: month[j].value,children: []};$.each(day, function(x) {if(formatterday(year[i].value,month[j].value) == 1 && day[x].value < 32) {var level3 = {label: day[x].label,value: day[x].value,children:[]};$.each(halfday, function(z) {var level4 = {label:halfday[z].label,value:halfday[z].value,};level3.children.push(level4);});level2.children.push(level3);}else if(formatterday(year[i].value,month[j].value) == 2 && day[x].value < 31){var level3 = {label: day[x].label,value: day[x].value,children:[]};$.each(halfday, function(z) {var level4 = {label:halfday[z].label,value:halfday[z].value,};level3.children.push(level4);});level2.children.push(level3);}else if(formatterday(year[i].value,month[j].value) == 3 && day[x].value < 30){var level3 = {label: day[x].label,value: day[x].value,children:[]};$.each(halfday, function(z) {var level4 = {label:halfday[z].label,value:halfday[z].value,};level3.children.push(level4);});level2.children.push(level3);}else if(day[x].value < 29){var level3 = {label: day[x].label,value: day[x].value,children:[]};$.each(halfday, function(z) {var level4 = {label:halfday[z].label,value:halfday[z].value,};level3.children.push(level4);});level2.children.push(level3);}});level1.children.push(level2);}});mydate_select.push(level1);});return mydate_select;
}function formatterday(year,month) {var bigmonth = [1,3,5,7,8,10,12];var smallmonth = [4,6,9,11];if(bigmonth.indexOf(month) >= 0)return 1;//大月份if(smallmonth.indexOf(month)>= 0 )return 2;//小月份else if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) return 3;//闰年二月else return 4;//非闰年二月
}