2014-10-17 90 views
-2

我想加一個輸入框成一個div和如下內追加格是我的代碼:另一個DIV

document.getElementById('locations').appendChild('<div id="'+lname+'"><input placeholder="'enter please'" type="text" name="newbutton"/><br/><br/></div>'); 
我不使用 innerHTML+=方法,因爲我以前創建的輸入框丟失的文本內容,而

使用它附加一個新的輸入框。

上面的代碼似乎不適合我。代碼有問題嗎?

+3

你的問題是什麼? – 2014-10-17 16:37:59

+0

您可以使用['insertAdjacentHTML'](https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML)而不是'innerHTML'。它不吃以前的HTML。儘管如此,你必須用'placeholder'解決一個問題。 – Teemu 2014-10-17 16:46:04

+0

http://www.w3schools.com/jsref/met_node_appendchild.asp – alquist42 2014-10-17 17:21:47

回答

2

你的代碼是完全錯誤的:.appendChild()方法沒有得到一個string作爲參數,它得到一個NodeElement。所以你應該首先創建元素,然後將它們追加到父級。正確的代碼是:

var container = document.getElementById('locations'), 
    children = document.createElement('div'), 
    input = document.createElement('input'); 

children.id = lname; 
input.placeholder = 'enter please'; 
input.type = 'text'; 
input.name = 'newbutton'; 

children.appendChild(input); 
container.appendChild(children);