1

我有一个 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>
4

3 回答 3

0

我想这与do-while循环有关。因为do while循环在检查while的条件之前会执行一次循环的内容。所以你的值会显示两次。

而如果您使用 while循环,它将在执行内容之前首先检查条件,并且不会在条件之前执行。

于 2013-10-31T05:04:53.960 回答
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);
于 2013-10-31T05:05:03.017 回答
0

看起来您没有关闭<option>标签。

此外,正如上面评论中提到的,有比手动写出标签更好的方法document.write。以这种方式手动编写 HTML 时,您更容易产生错误。

于 2013-10-31T05:00:50.463 回答