2013-02-17 158 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; 
}