如何在PHP中使用javascript加载页面时加载带有值的html <select>?</select>

时间:2011-05-04 08:44:45

标签: php javascript html-select

我遇到的问题是,无论何时首次加载页面或刷新页面时,如何使用值加载HTML <select>

我实际上正在尝试使用3个下拉菜单创建一个date_select,其中包括年,月和日,当月菜单或年菜单更改时,它将自动调整天数。

例如,当我选择3月份的日期为31日或4月时,日期将仅为30日。

我的问题是当页面首次加载时,日期菜单为空。我在onload上尝试了<select>,但它没有用。我是编程的初学者,所以即使是这样的简单练习我也遇到了麻烦。请帮忙。

date_select.php

<script type="text/javascript" >

 function loadDays() {
  var year = parseInt(document.getElementById('years').value);
  var month = document.getElementById('months').value;
  var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
  var days = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

  if ((year % 4) == 0)  days[1] = 29;

  var days_select = document.getElementById('days');
  days_select.options.length = 0;

  for(i in months) {
   if (month == months[i]) {
    for(var j = 1; j <= days[i]; j++ ) days_select.options[days_select.options.length] = new Option(j, j);
    break;
   }
  }
 }

</script>

<span style="display: table; ">
 <span style="display: table-cell; ">
  <select id="years" onchange="loadDays();">
   <?php 
    for($year = 1900; $year <= 2100; $year++ ) {
     if ($year == date('Y')) echo "<option value='$year' selected=''>" . $year . "</option>";
     else echo "<option value='$year'>" . $year . "</option>";
    }
   ?>
  </select>
 </span>
 &nbsp;
 <span style="display: table-cell; ">
  <select id="months" onchange="loadDays();">
   <?php 
    $months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" );

    foreach($months as $month){
     if ($month == date('M')) echo "<option value='$month' selected=''> " . $month . "</option>";
     else echo "<option value='$month'> " . $month . "</option>";
    }
   ?>
  </select>
 </span>
 &nbsp;
 <span style="display: table-cell; ">
  <select id="days" onload="loadDays();">

  </select>
 </span>
</span>

3 个答案:

答案 0 :(得分:4)

您应该考虑使用jQuery,这是一个功能强大的跨浏览器javascript库,可以让javascript编程更易于访问。

例如,它提供了一个函数,在插入javascript之前等待加载DOM内容(并且它比“onload”事件更好,因为它不支持加载图像)

在jquery中,你(几乎)总是将你的javascript包装在这个函数中

$(document).ready(function(){
         //Here goes your code
});

如果你需要javascript,你真的应该检查jQuery或其他框架

答案 1 :(得分:3)

我认为只要将javascript块移到这些跨度之下并选择然后在声明后立即调用它就足够了。

<span style="display: table; ">
...
</span>

<script type="text/javascript" >

 function loadDays() {
 ...
 }

 loadDays();
</script>

答案 2 :(得分:1)

尝试将onload属性放在body标签中,而不是select标签。

<body onload="loadDays();">