2014-10-17 91 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);