动态创建的<th>获取位置较低的原因是什么?

时间:2019-11-07 12:22:41

标签: javascript jquery html

下面是我使用jquery创建的<th>的代码段。

我的问题是,如何将动态创建的<th>放在下面创建的两个<td>之上。

我尝试搜索很多内容,但所有结果仅添加到末尾,而不是添加到<td>的顶部。

$(document).ready(
  function() {
    var noOfRow = document.getElementById("addItemTable").rows.length;
    var temp = document.getElementById("addItemTable");
    var table = temp.getElementsByTagName('tbody')[0];
    var row = table.insertRow(-1);
    var cell2 = row.insertCell(0);
    var cell3 = row.insertCell(1);
    cell2.innerHTML="this is inside table div";
    cell2.style="border: dashed;"
    cell3.innerHTML="this is inside another another div";
    cell3.style="border: dashed;"
    var thContent = '<th class="col2">' + '<br>' + 'test' + '&nbsp &nbsp' + '*' + '' + '</th>'
    var mainTable = document.getElementById("addItemTable");
    $('#addItemTable>tbody>tr').append(thContent);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>

1 个答案:

答案 0 :(得分:3)

您必须使用append的前置前缀:)

$(document).ready(
  function() {
    var noOfRow = document.getElementById("addItemTable").rows.length;
    var temp = document.getElementById("addItemTable");
    var table = temp.getElementsByTagName('tbody')[0];
    var row = table.insertRow(-1);
    var cell2 = row.insertCell(0);
    var cell3 = row.insertCell(1);
    cell2.innerHTML="this is inside table div";
    cell2.style="border: dashed;"
    cell3.innerHTML="this is inside another another div";
    cell3.style="border: dashed;"
    var thContent = '<th class="col2">' + '<br>' + 'test' + '&nbsp &nbsp' + '*' + '' + '</th>'
    var mainTable = document.getElementById("addItemTable");
    $('#addItemTable>tbody>tr').prepend(thContent);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
  <table id="addItemTable">
    <tbody>

    </tbody>
  </table>
</div>