使用JavaScript在HTML表格中添加行

时间:2018-06-16 01:31:46

标签: javascript html

我想在我的HTML代码中用JavaSctipt编写<td>标签。 我在主代码中构建了<table>,并且我想继续使用<script>,在分部中添加行。

<body>
  <table>
    <tr>
      <td>First</td>
    </tr>
    <div id="searchOutput"></div>
    <tr>
      <td>Last</td>
    </tr>
  </table>
  <script>
  document.getElementById("searchOutput").innerHTML = "<tr><td>Middle<td><tr>";
  </script>
</body>

问题是<script>以奇怪的方式创建了另一个表。

closure in perlfaq7 Chrome result

有没有办法在<table>中没有编写所有代码(包括<script>标记)的情况下添加行?

3 个答案:

答案 0 :(得分:2)

要在表格中插入新行,您可以使用表格new_env <- new.env() list2env(master,new_env) list2env(new_env$personalInfo,new_env) rm(personalInfo,envir = new_env) res <- as.data.frame(do.call(cbind,as.list(new_env))) # or as_tibble(as.list(new_env)) rm(new_env) res # fname id mname # 1 Jack 1551 B # 2 Yogesh 1033 NULL # 3 Steven 1061 J # 4 Richard 1262 I # 5 Thomas 1032 E # 6 Craig 1896 A # 7 David 1080 R # 8 Aman 1099 NULL # 9 Frank 1679 J # 10 Robert 1690 E str(res) # 'data.frame': 10 obs. of 3 variables: # $ fname:List of 10 # ..$ : chr "Jack" # ..$ : chr "Yogesh" # ..$ : chr "Steven" # ..$ : chr "Richard" # ..$ : chr "Thomas" # ..$ : chr "Craig" # ..$ : chr "David" # ..$ : chr "Aman" # ..$ : chr "Frank" # ..$ : chr "Robert" # $ id :List of 10 # ..$ : num 1551 # ..$ : num 1033 # ..$ : num 1061 # ..$ : num 1262 # ..$ : num 1032 # ..$ : num 1896 # ..$ : num 1080 # ..$ : num 1099 # ..$ : num 1679 # ..$ : num 1690 # $ mname:List of 10 # ..$ : chr "B" # ..$ : NULL # ..$ : chr "J" # ..$ : chr "I" # ..$ : chr "E" # ..$ : chr "A" # ..$ : chr "R" # ..$ : NULL # ..$ : chr "J" # ..$ : chr "E" insertRow()方法。 insertCell()方法创建一个空的insertRow()元素并将其添加到表中。 <tr>方法将单元格插入当前行。

请参阅以下代码:

&#13;
&#13;
insertCell()
&#13;
function addRows() {
  var table = document.getElementById( 'myTable' ),
      row = table.insertRow(0),
      cell1 = row.insertCell(0),
      cell2 = row.insertCell(1);

  cell1.innerHTML = 'Cell 1';
  cell2.innerHTML = 'Cell 2';
}
&#13;
table {
  border: 1px solid #999;
  border-collapse: collapse;
  width: 100%
}
td {
  border: 1px solid #999
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

某些表现是正确的; div不应该是表的直接子项。您可能会发现this question很有用。你有正确的想法,如果你只能实际替换div的HTML而不是简单填写它。那么,你可以将Last tr的ID设置为searchOutput。然后,像

>>> todays_shop_list = [{'item': 'apple', 'amount': 10, 'cost': 5}, 
...                     {'item': 'banana', 'amount': 12, 'cost': 6}, 
...                     {'item': 'strawberry', 'amount': 8, 'cost': 9}]

>>> x(todays_shop_list, 'apple')
{'item': 'apple', 'amount': 10, 'cost': 5}

答案 2 :(得分:1)