附加文本框和按钮

时间:2019-09-23 10:35:18

标签: javascript

如何创建文本框/文本字段和按钮

JavaScript

<script type="text/javascript">
function addItemTodo(){

  var value = document.getElementById('item1').value;
  var value2 = document.getElementById('item2').value;

  var my_table = document.getElementById('todo');
  var rows = my_table.getElementsByTagName("tr").length;
  row = my_table.insertRow(rows);
  cell1 = row.insertCell(0);
  cell2 = row.insertCell(1);
  cell1.innerHTML = value;
  cell2.innerHTML = value2;
}
</script>

HTML代码

<input type="text" id="item1" placeholder="item1" size="12">
  <input type="text" id="item2" placeholder="item2" size="14">
  <button id="add" onclick="addItemTodo()">Add</button>

<table border="1" style="width:50%" id="todo">
    <tr>
      <th>Input from 'item1'</th>
      <th>Input from 'item2'</th>
      <th>Text Box</th>
      <th>Button</th>  
    </tr>
</table>

当点击添加 按钮

时,如何附加文本框和按钮

1 个答案:

答案 0 :(得分:2)

您可以在Javascript中将新元素创建为字符串,然后使用insertCell(2)将它们添加到两个新单元格(insertCell(3).innerHTML)中,如下所示:

function addItemTodo() {
  var value = document.getElementById('item1').value;
  var value2 = document.getElementById('item2').value;

  var my_table = document.getElementById('todo');
  var rows = my_table.getElementsByTagName("tr").length;
  var row = my_table.insertRow(rows);
  row.insertCell(0).innerHTML = value;
  row.insertCell(1).innerHTML = value2;
  row.insertCell(2).innerHTML = "<input type='text' placeholder='xxx' class='text-box' />";
  row.insertCell(3).innerHTML = "<button>Text</button>";
  
}
.text-box {
  width: 50px;
}
<input type="text" id="item1" placeholder="item1" size="12">
<input type="text" id="item2" placeholder="item2" size="14">
<button id="add" onclick="addItemTodo()">Add</button>

<table border="1" style="width:50%" id="todo">
  <tr>
    <th>Input from 'item1'</th>
    <th>Input from 'item2'</th>
    <th>Text Box</th>
    <th>Button</th>
  </tr>
</table>