You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让jQuery年月选择器下拉框显示自定义文本或上次选中值

解决jQuery UI年月选择器默认显示最新年月的问题

问题分析

当前你的年月选择器在打开时会自动选中maxDate对应的年月(2023年4月),而你希望初始时显示通用提示文本,或者记住上次选中的年月值。defaultDate仅支持设置具体日期,直接用beforeShow没生效是因为需要在下拉框渲染完成后再修改选中状态。

解决方案1:初始显示通用提示文本

我们可以在beforeShow事件中,为月份和年份下拉框添加自定义的提示选项,并设置为选中状态,同时调整关闭按钮的逻辑,确保用户选择提示选项时不会设置无效日期。

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
    <title>Datepicker</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <style>
        #ui-datepicker-div{
            width: 20rem;
            left: 632px;
        }
        .ui-datepicker-calendar {
            display: none;
        }
        .datepicker{
            margin-top: 1rem;
            display: grid;
            justify-items: center;
            background: #333;
            padding: 1rem;
        }
        select > option{
            background-color: rgb(212, 212, 212);
        }
        .ui-datepicker-prev{
            background: white;
            cursor: pointer;
        }
        .ui-datepicker-next{
            background: white;
            cursor: pointer;
        }
        .ui-datepicker .ui-datepicker-buttonpane button{
            color: white;
            background: black;
        }
        .ui-datepicker .ui-datepicker-buttonpane button:hover{
            color: white;
            background: rgb(234, 176, 0);
        }
        .monthYearPicker{
            font-size: 1.5rem;
            height: 2rem;
            width: 20rem;
        }
        .monthYearPara{
            color: rgb(255, 255, 255);
        }
    </style>
</head>
<body>
    <div class="datepicker">
        <p class="monthYearPara">Pick Month & Year:</p>
        <input readonly name="myDate" class="monthYearPicker" placeholder=" Date Picker " />
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script>
        $(function() {
            $('.monthYearPicker').datepicker({
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
                minDate: new Date(2020, 0),
                maxDate: new Date(2023, 3),
                dateFormat: 'MM yy',
                beforeShow: function(input, inst) {
                    setTimeout(function() {
                        var monthSelect = inst.dpDiv.find('.ui-datepicker-month');
                        var yearSelect = inst.dpDiv.find('.ui-datepicker-year');
                        
                        if (!monthSelect.find('option[value="-1"]').length) {
                            monthSelect.prepend('<option value="-1">选择月份</option>');
                            yearSelect.prepend('<option value="-1">选择年份</option>');
                        }
                        
                        if ($(input).val() === '') {
                            monthSelect.val('-1');
                            yearSelect.val('-1');
                        }
                    }, 10);
                }
            }).focus(function() {
                var thisCalendar = $(this);
                $('.ui-datepicker-calendar').detach();
                $('.ui-datepicker-close').click(function() {
                    var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    
                    if (month !== '-1' && year !== '-1') {
                        thisCalendar.datepicker('setDate', new Date(year, month, 1));
                    }
                });
            });
        });
    </script>
</body>
</html>

解决方案2:记住上次选中的年月

通过本地存储保存用户上次选中的年月,每次打开选择器时自动选中该值;如果是第一次打开,则可以默认选中范围的起始年月。

修改后的核心代码

$(function() {
    var savedMonth = localStorage.getItem('selectedMonth');
    var savedYear = localStorage.getItem('selectedYear');

    $('.monthYearPicker').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        minDate: new Date(2020, 0),
        maxDate: new Date(2023, 3),
        dateFormat: 'MM yy',
        beforeShow: function(input, inst) {
            setTimeout(function() {
                var monthSelect = inst.dpDiv.find('.ui-datepicker-month');
                var yearSelect = inst.dpDiv.find('.ui-datepicker-year');
                
                if (savedMonth !== null && savedYear !== null) {
                    monthSelect.val(savedMonth);
                    yearSelect.val(savedYear);
                } else {
                    monthSelect.val('0');
                    yearSelect.val('2020');
                }
            }, 10);
        },
        onClose: function(dateText, inst) {
            var month = inst.dpDiv.find('.ui-datepicker-month :selected').val();
            var year = inst.dpDiv.find('.ui-datepicker-year :selected').val();
            localStorage.setItem('selectedMonth', month);
            localStorage.setItem('selectedYear', year);
        }
    }).focus(function() {
        var thisCalendar = $(this);
        $('.ui-datepicker-calendar').detach();
        $('.ui-datepicker-close').click(function() {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            thisCalendar.datepicker('setDate', new Date(year, month, 1));
        });
    });

    if (savedMonth !== null && savedYear !== null) {
        $('.monthYearPicker').datepicker('setDate', new Date(savedYear, savedMonth, 1));
    }
});

关键修复点

  1. 移除冲突依赖:删除重复引入的旧版本jQuery和jQuery UI,避免版本冲突导致异常。
  2. 延迟修改下拉框:用setTimeout在beforeShow中等待下拉框渲染完成后再修改选中状态,确保DOM元素已存在。
  3. 避免重复添加选项:判断提示选项是否已存在,防止每次打开选择器都重复添加。
  4. 持久化选中状态:利用本地存储保存用户选择,实现记忆功能。

内容的提问来源于stack exchange,提问作者RMT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:27:59