下面是我创建 <th>
的代码片段使用 jquery。
我的问题是,如何放置动态创建的 <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' + '   ' + '*' + '' + '</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>
最佳答案
你必须使用 prepend insead of 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' + '   ' + '*' + '' + '</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>
关于javascript - 动态创建的 <th> get 的较低位置为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748709/