2013-10-31 385 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