0

我有 3 个下拉菜单,它们的功能是选择一个日期,然后当 .onchange 发生时,它会用当前日期填充文本框。我将如何使它自动执行此操作 .onload

这就是我用来更改日期的 .onchange

function showDate(){
        var combos = [
        document.getElementById('daydropdown'),
        document.getElementById('monthdropdown'),
        document.getElementById('yeardropdown')
    ];

    var values = [], combo, value;

    for(var i = 0; i < combos.length; i++){

        combo = combos[i];
        value = combo.options[combo.selectedIndex].innerHTML;
        values.push(value);
    }
    document.getElementById('date').value = values.join('/');
}

// event handlers:
document.getElementById('daydropdown').onchange =
   document.getElementById('monthdropdown').onchange =
       document.getElementById('yeardropdown').onchange = showDate;
document.getElementById('daydropdown').onload =
   document.getElementById('monthdropdown').onload =
       document.getElementById('yeardropdown').onload = showDate;
</script>
<script type="text/javascript">
4

2 回答 2

0

我已经为您设置了一个在 JSFiddle 中运行良好的改进解决方案,看看这是否有帮助。

http://jsfiddle.net/mWEw9/6/

基本变化如下:

window.onload = setDateListener;

function setDateListener() {
    showDate();

    document.getElementById('daydropdown').onchange =          
    document.getElementById('monthdropdown').onchange =
    document.getElementById('yeardropdown').onchange = showDate;
}
于 2013-06-07T14:25:40.707 回答
0

只需将事件处理程序挂钩到onload事件并调用showDate()那里以在加载时设置下拉菜单。

window.addEventListener("load",function() {
  document.getElementById('daydropdown').onchange =
     document.getElementById('monthdropdown').onchange =
        document.getElementById('yeardropdown').onchange = showDate;
  document.getElementById('daydropdown').onload =
     document.getElementById('monthdropdown').onload =
        document.getElementById('yeardropdown').onload = showDate;
  showDate();
});
于 2013-06-07T14:11:46.047 回答