2017-07-05 67 views
0

我想單擊按鈕後,將testTag變量顯示給div。當我點擊它時,只顯示選項標籤的標籤,而不是完整的選擇標籤。 請幫忙!這是我的代碼。如何顯示HTML標記從JavaScript變量到div ID?

function showDropdown() { 
 
\t \t 
 
\t var textTag = "<select>"; 
 
\t var textOptions = ["option1","option2","option3"]; 
 
\t 
 
\t for (i = 0; i < textOptions.length; i++) { 
 
\t \t textTag += '<options value="' + textOptions[i] + '">' + textOptions[i] + "</options>"; 
 
\t \t 
 
\t } 
 
\t 
 
\t textTag += "</select>"; 
 
\t \t 
 
\t document.getElementById("dropdownTest").innerHTML= textTag; 
 
\t console.log(textTag); 
 
\t }
<!doctype html> 
 
<html> 
 
<head> 
 
<meta charset="utf-8"> 
 
<title>Show dropdown</title> 
 
</head> 
 

 
<body> 
 
<input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()"> 
 
<div id="dropdownTest"></div> 
 

 
</body> 
 
</html>

+0

我投票,因爲這個問題只是一個錯字,關閉了這個問題。 –

回答

4

這就是所謂的<option>,不<options>

function showDropdown() { \t 
 
    var textTag = "<select>"; 
 
    var textOptions = ["option1","option2","option3"]; 
 
\t 
 
    // declare "i"! 
 
    for (var i = 0; i < textOptions.length; i++) { 
 
     // change this line 
 
     textTag += '<option value="' + textOptions[i] + '">' + textOptions[i] + "</option>";  \t \t 
 
    } 
 
\t 
 
    textTag += "</select>"; 
 
\t \t 
 
    document.getElementById("dropdownTest").innerHTML = textTag; 
 
    console.log(textTag); 
 
}
<!doctype html> 
 
<html> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>Show dropdown</title> 
 
    </head> 
 
    <body> 
 
    <input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()"> 
 
    <div id="dropdownTest"></div> 
 
    </body> 
 
</html>

+0

哇。即時把我的頭髮脫掉。我剛開始學習JavaScript。謝謝您的幫助! – kreatusJohn

+0

@ user3080440其實,這是一個HTML錯誤,而不是JavaScript錯誤。 –