下拉列表中的选定值在下拉列表中显示两次

Selected values in dropdown display two times in dropdown

本文关键字:下拉列表 两次 显示      更新时间:2023-09-26

我有一个javascript下拉列表,它显示所选值和其他值,但所选值在下拉列表中显示2次,它应该显示1次。请任何人帮助我纠正 problem.eg。如果只有 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);