0

我设法使用以下小提琴创建了一个 javascript 下拉列表:

(function() {
    var calendar = [
        ["January", 31],
        ["February", 28],
        ["March", 31],
        ["April", 30],
        ["May", 31],
        ["June", 30],
        ["July", 31],
        ["August", 31],
        ["September", 30],
        ["October", 31],
        ["November", 30],
        ["December", 31]
        ],
        cont = document.getElementById('calendar-container');
    // setup
    var sel_year = document.createElement('select'),
        sel_month = document.createElement('select'),
        sel_day = document.createElement('select');

    function createOption(txt, val) {
        var option = document.createElement('option');
        option.value = val;
        option.appendChild(document.createTextNode(txt));
        return option;
    }

    function clearChildren(ele) {
        while (ele.hasChildNodes()) {
            ele.removeChild(ele.lastChild);
        }
    }

    function recalculateDays() {
        var month_index = sel_month.value,
            df = document.createDocumentFragment();
        for (var i = 0, l = calendar[month_index][1]; i < l; i++) {
            df.appendChild(createOption(i + 1, i));
        }
        clearChildren(sel_day);
        sel_day.appendChild(df);
    }

    function generateMonths() {
        var df = document.createDocumentFragment();
        calendar.forEach(function(info, i) {
            df.appendChild(createOption(info[0], i));
        });
        clearChildren(sel_month);
        sel_month.appendChild(df);
    }

    sel_month.onchange = recalculateDays;

    generateMonths();
    recalculateDays();

    cont.appendChild(sel_year);
    cont.appendChild(sel_month);
    cont.appendChild(sel_day);
}());

http://jsfiddle.net/rlemon/j2kzv/

但是我想修改它以默认显示当前月份和日期。有什么建议么?

4

1 回答 1

0

这样的事情会起作用:http: //jsfiddle.net/j2kzv/24/

在您创建选项时,我只是添加了对当前日期的检查,并没有太大变化:

calendar.forEach(function(info, i) {
            var selected = (currentDate.getMonth() === i) ? true : false;
            df.appendChild(createOption(info[0], i, selected));
});

然后在构建每个选项时添加一个选定的检查。

function createOption(txt, val, selected) {
    var option = document.createElement('option');
    option.value = val;
    option.selected = selected;
    option.appendChild(document.createTextNode(txt));
    return option;
}

为了简单起见,我还更新了循环的日期函数以使用序号 1 而不是 0 作为复选框值

于 2012-12-10T21:38:12.937 回答