[英]add td element to tr with id
幾乎就是標題所說的。 我有html documnet
<table>
<tr>
<td id="1"></td>
</tr>
</table>
設置並希望javascript函數在前一個下添加<td id="2"></td>
,所以看起來像。
<table>
<tr>
<td id="1"></td>
<td id="2"></td>
</tr>
</table>
使用jquery:
$(document).ready(function(){
$('#1').parent().append('<td id="2">2</td>');
});
javascript(Pure) insertCell()
方法用於將新單元格插入表格行。
使用insertCell()在表行的末尾插入包含內容的新單元格:
var row = document.getElementsByTagName("tr")[0];
var x = row.insertCell(-1);
x.innerHTML="New cell";
你也可以使用Javascript .appendChild
:
var parenttbl = document.getElementsByTagName("tr");
var newel = document.createElement('td');
var elementid = document.getElementsByTagName("td").length
newel.setAttribute('id',elementid);
newel.innerHTML = "New Inserted"
parenttbl[0].appendChild(newel);
更新:
HTML:
<table>
<tr id="myrow">
<td id="1">Hello</td>
</tr>
<tr>
<td id="1">Hello</td>
</tr>
<tr>
<td id="1">Hello</td>
</tr>
</table>
使用Javascript:
var parenttbl = document.getElementById("myrow");
var newel = document.createElement('td');
var elementid = document.getElementsByTagName("td").length
newel.setAttribute('id',elementid);
newel.innerHTML = "New Inserted"
parenttbl.appendChild(newel);
不需要使用jQuery來做這么簡單的事情,這樣做:
var tbl = document.querySelector("table");
var row0 = tbl.rows[0];
要么
var row0 = document.querySelector("#1");
然后插入您的單元格:
var cell1=row0.insertCell(1);//the 1 here is the cell index
cell1.id="2";
為了管理DOM元素,我通常提供使用本機JavaScript的代碼,而不是使用jQuery或任何其他JavaScript框架。
function addField () {
var myTable = document.getElementById("myTable");
var currentIndex = myTable.rows.length;
var currentRow = myTable.insertRow(-1);
var a ;
var currentCell= currentRow.insertCell(-1);
currentCell.style.height="25px";
currentCell.style.width="20px";
globalCheck=globalCheck+1;
currentCell.innerHTML="<input id=\"check"+globalCheck+"\" type=\"checkbox\"></input>";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.