2

我使用了来自http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/ html-javascript/ 的代码。我的代码是这样的:

<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add() {

    for (i=1; i<=5; i++)
      {
        //Create an input type dynamically.
        var element = document.createElement("input");
     
        //Assign different attributes to the element.
        element.setAttribute("type", i);
        element.setAttribute("name", i);
        element.setAttribute("value", i);
     
     
        var foo = document.getElementById("fooBar");
     
        //Append the element in page (in span).
        foo.appendChild(element);
      }

 
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<INPUT type="button" value="Add" onclick="add()"/>
     
<span id="fooBar">&nbsp;</span>
     
</FORM>
</BODY>
</HTML>

该代码有效。但不是水平添加它,我希望每个新文本字段都添加到一个新行中。我尝试在循环函数中使用</script><br/><script><html><br/></html>document.write("\n")document.write("\r\n"),但它不像我想要的那样工作。我应该怎么办?

4

4 回答 4

4

为什么不这样做呢?

var br = document.createElement("br");
foo.appendChild(br);
于 2012-09-01T04:13:45.520 回答
1

您可以更改输入的显示样式。

function add() {

    for (i=1; i<=5; i++)
      {
        //Create an input type dynamically.
        var element = document.createElement("input");

        //Assign different attributes to the element.
        element.setAttribute("type", i);
        element.setAttribute("name", i);
        element.setAttribute("value", i);
        element.style.display = "block";

        var foo = document.getElementById("fooBar");

        //Append the element in page (in span).
        foo.appendChild(element);
      }
}

祝你好运!我建议你开始使用 jQuery 来处理你的 javascript 任务。

于 2012-09-01T04:13:34.817 回答
0

您可以尝试在输入元素之后添加一个新的 br 元素。

  for (i=1; i<=5; i++)
  {
    //Create an input type dynamically.
    var element = document.createElement("input");

    //Assign different attributes to the element.
    element.setAttribute("type", i);
    element.setAttribute("name", i);
    element.setAttribute("value", i);

    var brElement = document.createElement("br");

    var foo = document.getElementById("fooBar");

    //Append the element in page (in span).
    foo.appendChild(element);
    foo.appendChild(brElement );
  }
于 2012-09-01T04:14:19.307 回答
0

您可以简单地将其添加到您的 CSS

input{display:block;}
于 2012-09-01T04:16:09.450 回答