一个页面多个地方使用日期组件 - layui.laydate时,动态设置最大最小值

开发页面中使用 laydate日期组件设置日期。

<div class="">
    日期1:
    <input type="text" class="J-startTime" value="" placeholder="请选择开始日期" readonly="readonly">
    <span class="from-to">&nbsp-&nbsp</span>
    <input type="text" class="J-endTime" value="" placeholder="请选择结束日期" readonly="readonly">
</div>
<div class="">
    日期2:
    <input type="text" class="J-startTime" value="" placeholder="请选择开始日期" readonly="readonly">
    <span class="from-to">&nbsp-&nbsp</span>
    <input type="text" class="J-endTime" value="" placeholder="请选择结束日期" readonly="readonly">
</div>

需求:

1、点击“开始日期”后,对应的“结束日期”默认等于“开始日期”;

2、对应的“结束日期”只能选择“开始日期”之后的日期(图中红框中的日期不可选)。

方法:

1、由于页面中多次使用日期组件,所以通过循环遍历渲染日期;

2、循环时,通过数组endDate+index将“开始日期”和“结束日期”对应;

3、通过endDate[index].config.min设置“结束日期”的最小值。(通过startDate[index].config.max可以设置开始日期的最大值)

$(function () {
    var endDate=[];
    $('.J-startTime').each(function(index){
        var _this=this;
        laydate.render({
            elem: _this,
            done: function(value, date){
                $(_this).nextAll('.J-endTime').val(value);
                endDate[index].config.min ={
                    year:date.year,
                    month:date.month-1, //关键
                    date: date.date,
                };
            }
        });
    });
    $('.J-endTime').each(function (index) {
        var _this=this;
        endDate[index]=laydate.render({
            elem:_this,
        });
    });
});

注意:

1、endDate[index].config.min是一个对象,必须分别设置:年、月、日;

2、date中的月从1开始,而endDate[index].config.min中的月从0开始,所以需在date.month-1基础上赋值。

猜你喜欢

转载自blog.csdn.net/g229191727/article/details/88812746