2013-02-17 159 views
0

我不确定是否有我的while循环或我的代码的innerHTML部分有问题,但我不能显示下拉列表中的div标签单击提交按钮时。任何人都可以看到它有什么问题。虽然循环和innerHTML

<html> 
<head> 
<script type="text/javascript"> 

function getvalue() { 
number = document.getnumber.input.value; 
document.getElementById("result").value = number; 
} 
</script> 

</head> 
<body> 

<script> 
function generatedropdown() { 
html = '<select name="select" id="i">'; 
while (i < number) {    
html+='<option>Test 1</option>'; 
html+='<option>Test 2</option>'; 
html+='<option>Test 3</option>'; 
html+='<option>Test 4</option>'; 
html+='<option>Test 5</option>';   
i++; 
} 
html+='</select>'; 
document.getElementById("my-output").innerHTML = html; 
} 
</script> 


<form name="getnumber"> 
Input number: <input type="text" name="input"> 
<input type="button" value="Next" onClick="getvalue()"> 
</form> 


<form id="showlists"> 
Number entered: <input type="text" id="result" readonly="readonly">  
<input type="button" value="Show lists" onClick="generatedropdown()"> 
<div id="my-output">Generated List:</div> 
</form> 
</body> 
</html> 
+1

当你调用generatedropdown,数量变量没有定义。 – sdespont 2013-02-17 10:43:16

+0

它应该在调用getvalue之后定义,但仍然不起作用。 – washoku 2013-02-17 10:46:59

回答

5

的几个问题:

  • 你从来没有设置i的初始值,所以代码将抛出一个错误,因为你想读一个全球性的该值你从未设置或宣布。

  • 你依靠getvalue已被调用初始化number,我不会指望。

  • 你依靠隐式字符串 - >数字转换,我不推荐;使用parseInt解析用户提供的号码。

  • (可选)您的循环也正是for结构是专为,而不是while(虽然while会工作,如果你初始化i)。

  • 由于您从未声明过变量,因此您正在堕入The Horror of Implicit Globals

我建议阅读一篇好的JavaScript入门书或教程,掌握基础知识。

这里有一个最小更新:

function generatedropdown() { 
    // Declare your variables 
    var html, i, number; 

    // Get the number, and convert it from a decimal string 
    // to a number explicitly rather than relying on implicit 
    // coercion 
    number = parseInt(document.getvalue.input.value, 10); 

    // Probably bail if it's not a number 
    if (isNaN(number)) { 
     return; 
    } 

    // (Optional, but you were doing it) Show the number 
    document.getElementById("result").value = number; 

    // Build your HTML 
    html = '<select name="select" id="i">'; 

    // This is exactly what `for` loops are for 
    for (i = 0; i < number; ++i) { 
     html+='<option>Test 1</option>'; 
     html+='<option>Test 2</option>'; 
     html+='<option>Test 3</option>'; 
     html+='<option>Test 4</option>'; 
     html+='<option>Test 5</option>';   
    } 
    html+='</select>'; 
    document.getElementById("my-output").innerHTML = html; 
}