簡體   English   中英

下拉菜單中的選定值在下拉菜單中顯示兩次

[英]Selected values in dropdown display two times in dropdown

我有一個javascript下拉列表,它顯示選定的值和其他值,但是選定的值在下拉列表中顯示2次,它應該只顯示1次。請任何人幫助我糾正問題。例如。 如果只有3個值2013、2014.2015,而我選擇2013,但它會顯示2013-所選值2013 2013 2014 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>

看來您沒有關閉<option>標記。

另外,如上面的評論中所述,與使用document.write手動寫出標記相比,還有更好的方法來執行此操作。 通過這種方式手動編寫HTML時,您更容易產生錯誤。

我想這與do-while循環有關。 因為do while循環會在檢查while條件之前執行一次循環的內容,因此您的值將顯示兩次。

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

您需要在循環中放置一個條件,讓它知道它需要跳過選定的值,請允許我在下面進行演示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM