如何在javascript中创建输入文本框

时间:2016-05-15 23:41:13

标签: javascript

程序显示的表格中输入了默认文本。我想知道如何用带有id的输入文本框替换它。谢谢

<html>
<body>

</body>
<script>
function tableCreate(){
var body = document.body,
tbl  = document.createElement('table');
tbl.style.width  = '100px';
tbl.style.border = '2px solid black';
var n=5
for(var i = 0; i < n; i++){
    var tr = tbl.insertRow()
    var td = tr.insertCell(0);
    var tf = tr.insertCell(0);  
    td.appendChild(document.createTextNode('input'));
    tf.appendChild(document.createTextNode('input'));
    td.style.border = '2px solid black';
    tf.style.border = '2px solid black';
    }

body.appendChild(tbl);
}
tableCreate();
</script>
</html>

1 个答案:

答案 0 :(得分:1)

document.createElement("input")替换为document.createTextNode("input");创建form元素,在创建的每个name元素中包含input属性属性;将id设置为"input-a" + i"input-b" + i;将input type="submit"附加到form元素;将创建的table附加到form元素

&#13;
&#13;
<body>
  <script>
    function tableCreate() {
      var body = document.body,
        tbl = document.createElement('table');
      tbl.style.width = '100px';
      tbl.style.border = '2px solid black';
      var n = 5
      for (var i = 0; i < n; i++) {
        var tr = tbl.insertRow(); var td = tr.insertCell(0);
        var tf = tr.insertCell(0);
        var input = document.createElement('input');
        input.name = "input-a" + i;
        input.id = "input-a" + i;
        input.value = "";
        var clone = input.cloneNode();
        clone.name = "input-b" + i;
        clone.id = "input-b" + i;
        td.appendChild(clone);
        tf.appendChild(input);
        td.style.border = '2px solid black';
        tf.style.border = '2px solid black';
      }
      var form = document.createElement("form");
      form.appendChild(tbl);
      body.appendChild(form);
      var submit = document.createElement("input");
      submit.type = "submit";
      form.appendChild(submit)
    }
    tableCreate(); 
  </script>
</body >
&#13;
&#13;
&#13;