5

我正在寻找一个标准的 HTML 选择菜单来选择您的出生日期。日月年。有人可以指出我正确的方向来使用 jQuery 根据选择的年份/月份等来格式化月份中正确的天数吗?是否有任何插件可以实现这一点,或者我将如何自己编写?任何意见,将不胜感激。

4

2 回答 2

11

基本上,您需要三个选择框(日、月、年)以及年月的 onchange 事件。

年月选择框的更改需要更新天数,因为这些取决于年月。要计算给定月份/年份的天数,本文将有所帮助。

http://www.electrictoolbox.com/javascript-days-in-month/

工作示例JSFIDDLE

html

<select id="days"></select>
<select id="months"></select>
<select id="years"></select>

js

$(function() {

    //populate our years select box
    for (i = new Date().getFullYear(); i > 1900; i--){
        $('#years').append($('<option />').val(i).html(i));
    }
    //populate our months select box
    for (i = 1; i < 13; i++){
        $('#months').append($('<option />').val(i).html(i));
    }
    //populate our Days select box
    updateNumberOfDays(); 

    //"listen" for change events
    $('#years, #months').change(function(){
        updateNumberOfDays(); 
    });

});

//function to update the days based on the current values of month and year
function updateNumberOfDays(){
    $('#days').html('');
    month = $('#months').val();
    year = $('#years').val();
    days = daysInMonth(month, year);

    for(i=1; i < days+1 ; i++){
            $('#days').append($('<option />').val(i).html(i));
    }
}

//helper function
function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}
于 2013-09-19T17:49:44.387 回答
1

jQuery UI 库有一个出色且高度可定制的小部件,称为日期选择器。小部件的页面以及您可以用作参考的代码都可以在这里找到:http: //jqueryui.com/datepicker/

您只需要在标题中包含 jQuery 和 jQuery UI 库,如下所示:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

然后,创建一个普通的文本框:

<input name="Date" id="Date" value="" />

然后使用以下代码初始化日期选择器:

<script type="text/javascript">

    $(function() {
        $("#Date").datepicker({
            changeMonth: true,
            changeYear: true
            });
    };

</script>

我在 datepicker 小部件上添加的选项允许您轻松跳转到给定的月份/年份,这对于几年前出生的人来说是必需的。

于 2013-09-19T17:51:15.243 回答