2013-01-05 35 views
0

我試圖在使用JavaScript單擊按鈕時動態地在網頁中插入文本框。我是JavaScript的初學者。我試圖在Chrome,Firefox和Opera中執行該程序(已啓用JavaScript)。但是,當我單擊按鈕時,程序不會插入文本框。我試圖在Eclipse中運行相同的代碼,Eclipse中的HTTP預覽器運行相同的代碼。任何人都可以告訴我爲什麼發生這種情況,以及如何在瀏覽器中執行相同的代碼?Javascript程序在Eclipse中運行,但不在Notepad ++中

下面是代碼我已經使用:

<html> 
<head> 
<title>Doing some random programming</title> 
</head> 
<body> 
Add input elements here: 
<br/> 
<input type = "button" value = "Add another element" id = "AddButton" onClick = "AddTextBox()" /> 
<div id = "Division"></div> 
<script type = "text/javascript"> 
<!-- 
//var addButton = document.getElementById('AddButton'); 
function AddTextBox() 
{  
    var divis = document.getElementById('Division'); 
    var inputTxt = document.createElement("<input type = \"text\" />"); 
    var div = document.createElement('div'); 
    //input.type = "text";  
    div.appendChild(inputTxt); 
    divis.appendChild(div); 
} 
//--> 
</script> 
<noscript> 
    Needs javascript 
</noscript> 
</body> 
</html> 

回答

3

createElement方法採用的元件類型,而不是HTML字符串的名稱。

var inputTxt = document.createElement("<input type = \"text\" />"); 

應該

var inputTxt = document.createElement("input"); 

或者(如果你想明確說明type="text",你並不需要,因爲它是默認):

var inputTxt = document.createElement("input"); 
inputTxt.setAttribute('type', 'text'); 
+0

非常感謝!它有幫助。 – TheRookierLearner

相關問題