2

Please let me know if this is a duplicate post, but I was not able to find a solution to my issue. Its gotta be something simple...

I'm trying to use javascript to build a form. The html for the form is as follows:

<form>
  Time: <input type="time"> <br>
  Performer: <input type="text"><br>
  Link: <input type="text"><br>
  <input type="submit" value="Submit">
</form>

what I'm trying to do is build this exact form using javascript, but the elements are all showing up on the same line. Here's my javascript function:

function addPerformance(){
var brk = document.createElement("br");
var form = document.createElement("form");

//create time element
var time = document.createElement("input");
time.setAttribute("type", "time");
form.appendChild(time);
form.appendChild(brk);

//create perfomer element
var perf = document.createElement("input");
perf.setAttribute("type", "text");
form.appendChild(perf);
form.appendChild(brk);

//create link element
var link = document.createElement("input");
link.setAttribute("type", "text");
form.appendChild(link);
form.appendChild(brk);

//create submit element
var sub = document.createElement("input");
sub.setAttribute("type", "submit");
sub.setAttribute("value", "Submit");
form.appendChild(sub);
form.appendChild(brk);

document.body.appendChild(form);
}

"form.appendChild(brk)" is what I thought would add those line breaks like in the html example but its not working. Ultimately, I just want each element of the form to be in a single column. Any help would be greatly appreciated, thanks!

4

1 回答 1

6

当您form.appendChild(brk);第二次调用时,它将引用的HTMLElementbrk从它所在的位置移动到新位置;即首先将其删除。

改为追加克隆

 form.appendChild(brk.cloneNode());
于 2013-08-05T14:24:08.860 回答