layui时间控件 laydate 重置失效

  • 问题描述
  • 页面代码
  • 问题处理

问题描述

layui日期控件laydate引入页面后,页面开始时间小于结束时间,结束时间最大为当前时间,展示效果如图,第一次选择开始时间和结束时间

layui时间控件 laydate 重置失效_前端


layui时间控件 laydate 重置失效_重置_02


layui时间控件 laydate 重置失效_重置_03


重置之后第二次选择开始时间和结束时间,效果如图

layui时间控件 laydate 重置失效_layui_04


开始时间的最大日期不在是4.15号,而是上次选择的4.13号,我们再看结束时间

layui时间控件 laydate 重置失效_layui_05


结束时间的最小日期不再是默认的 1900-01-01,而是第一次选择的开始时间4.5号,这样是不是很奇怪呢?

页面代码

<li class="input-daterange input-group">
操作时间:
<input type="text" name="createStartDate" readonly id="createStartDate"/>

<input type="text" name="createEndDate" readonly id="createEndDate"/>
</li>

js代码

var startDate;
var endDate;
function initLaydate() {
layui.use('laydate', function() {
var laydate = layui.laydate;
startDate = laydate.render({
elem: '#createStartDate',
max: $('#createEndDate').val(),
type: 'datetime',
theme: 'molv',
trigger: 'click',
done: function (value, date) {
// 结束时间大于开始时间
if (value !== '') {
endDate.config.min.year = date.year;
endDate.config.min.month = date.month - 1;
endDate.config.min.date = date.date;
} else {
endDate.config.min.year = '';
endDate.config.min.month = '';
endDate.config.min.date = '';
}
}
});
endDate = laydate.render({
elem: '#createEndDate',
//min: $('#createEndDate').val(),
max:$.common.getNowFormatDate(),
type: 'datetime',
theme: 'molv',
trigger: 'click',
done: function (value, date) {
// 开始时间小于结束时间
if (value !== '') {
startDate.config.max.year = date.year;
startDate.config.max.month = date.month - 1;
startDate.config.max.date = date.date;
} else {
startDate.config.max.year = '';
startDate.config.max.month = '';
startDate.config.max.date = '';
}
}
});
})
}
getNowFormatDate: function() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}

通过看代码整体上感觉没有问题,那么问题在哪儿呢?

问题处理

通过参照layui官网文档 日期控件,也没能找到原因,于是去百度搜索,看到有人说是重置只能清除input框的内容,但是不能清除日期控件的动态时间限制,那么怎么处理呢?网上的方案是重写重置函数,增加 endDate.config.min=startDate.config.min;
startDate.config.max=endDate.config.max;代码

function reset() {
$.form.reset();
endDate.config.min=startDate.config.min;
startDate.config.max=endDate.config.max;
}

采用之后却发现第二次问题是解决了但是第三次、第四次重置之后问题仍然存在,最后多方查找没有方案,后来自己探索发现再次初始化一下时间插件,代码如下

function reset() {
$.form.reset();
endDate.config.min=startDate.config.min;
startDate.config.max=endDate.config.max;
initLaydate();
}

问题解决,圆满。