2013-10-31 371 views
1

我有一個javascript下拉菜單它顯示選定的值和其他值,但選定的值顯示2倍下拉它應該顯示ony 1 time.Pls任何一個幫助我糾正問題。例如。 如果只有3個值2013,2014.2015and我選擇2013 但它顯示了2013-選定值 2015年在下拉列表中選擇的值顯示兩次下拉

<script type="text/javascript"> 
function autoYear() { 
    var time = new Date(); 
    var year = time.getYear(); 

    if (year < 1900) { 
    year = year + 1900; 
    } 

    var date = year - 1; /*change the '25' to the number of years in the past you want to show */ 
    var future = year + 10; /*change the '10' to the number of years in the future you want to show */ 

    document.writeln ("<form><select id='year_<?php echo $row->id ?>' name='year_<?php echo $row->id ?>' ><option value=\"\"><?php echo $row->year; ?>"); 
    do { 
    date++; 
    document.write ("<option value=\"" +date+"\">" +date+ ""); 
    } 
    while (date < future) 
    document.write ("</select></form>"); 
} 
</script> 
<script type="text/javascript"> 
    autoYear(); 
</script> 
+0

此下拉只顯示年。芒果,蘋果和橘子從哪裏來?並且使用'document.write()是如此1990年代 - 請學習現代Javascript。 – Barmar

回答

0

看起來你不關閉你的<option>標籤。

另外,正如上面的評論中提到的,有更好的方法可以做到這一點,而不是用document.write手動書寫標籤。以這種方式手動編寫HTML時,您更容易產生錯誤。

0

我想它已經與do-while循環做。因爲while循環在檢查while的條件之前執行循環的內容一次。因此,您的值將顯示兩次。

而如果您使用while循環,它將在執行內容之前首先檢查條件,並且不會在條件之前執行。

0

您需要將有條件在你的循環,讓它知道,它需要跳過選擇的值,請允許我在下面演示:

var date = year - 1; /*change the '25' to the number of years in the past you want to show */ 
var future = year + 10; /*change the '10' to the number of years in the future you want to show */ 

document.writeln ("<form><select id='year_<?php echo $row->id ?>' name='year_<?php echo $row->id ?>' ><option value=\"\"><?php echo $row->year; ?>"); 

do { 
    date++; 
    if (date != <?php echo $row->year; ?>) { 
     document.write ("<option value=\"" +date+"\">" +date+ ""); 
    } 
} 
while (date < future); 
+0

其工作:感謝francisco.preller – user2935177