2011-05-04 49 views
3

我在加載HTML <select>時遇到問題,無論何時頁面首次加載或刷新時。如何在PHP中使用javascript加載頁面時使用值加載html <select>?

我實際上是想用3個下拉菜單創建一個date_select,其中包括年份,月份和日期,其中月份菜單或年份菜單被更改時會自動調整天數。

例如,當我選擇3月份時,日期爲31或4月,日期將僅爲30天。

我的問題是當第一次加載頁面時,菜單是空的。我在<select>上試過onload,但沒有奏效。我是編程的初學者,所以即使是像這樣簡單的練習,我也遇到了麻煩。請幫忙。

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> 

回答

1

嘗試把onload屬性body標籤,而不是選擇標籤。

<body onload="loadDays();"> 
+0

謝謝老兄......它的工作! – 2011-05-04 09:09:17

3

我認爲它應該是足夠的,如果你只是移動你的JavaScript塊下面的跨度和選擇,然後調用你的函數後聲明。

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

<script type="text/javascript" > 

function loadDays() { 
... 
} 

loadDays(); 
</script> 
3

您應該考慮使用jQuery,JavaScript庫,試圖使Javascript編程更容易獲得一個強大的和跨瀏覽器。

例如,它提供了對DOM含量等待在它插入的JavaScript(和它是比「的onload」事件更好,因爲它不用於waith要加載圖像)

之前加載的函數

在jQuery的你(幾乎)總是包裹你的JavaScript在這個函數

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

如果你需要的JavaScript,你真的應該檢查的jQuery或其他框架

相關問題