2012-12-10 62 views
0

我已成功地創建使用下面搗鼓一個javascript下拉:日曆的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/

但是我想修改它默認顯示當前的月份和日期。有什麼建議麼?

回答

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; 
} 

我還更新的日期功能for循環使用的複選框的值的序1,而不是0爲簡單起見