Reproduction picture:
Code:
js dynamically add table data_2.html
The code copy is as follows:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js dynamically adds table data_2 Implementation using insertRow and insertCell methods</title>
<script type="text/javascript">
var mailArr = [
{ "title": "A C# problem", "name": "Zhang San", "date": "2014-03-21" },
{ "title": "A javascript problem", "name": "Li Si", "date": "2014-03-21" },
{ "title": "A C question", "name": "55", "date": "2014-03-21" },
{ "title": "A C++ question", "name": "Zhao Liu", "date": "2014-03-21" }
];
var tab = null;
window.onload = function () {
loadTab();
//Select all
document.getElementById("selA").onclick = function() {
if (document.getElementById("selA").checked == true) {
seleAll(tab, true);
} else {
seleAll(tab, false);
}
};
//Delete all selected
document.getElementById("delSel").onclick = function() {
//Transfer all input controls (except the last checkbox that is selected)
var chks = document.getElementsByTagName('input');
for (var i = chks.length - 2; i >=0; i--) {
var chk = chks[i];
if (chk.checked==true) {
//Select row deletion processing
var rowNow = chk.parentNode.parentNode;
rowNow.parentNode.removeChild(rowNow);
} else {
alert("really");
}
}
};
};
function loadTab() {
tab = document.getElementById("tb");
//Add mailArr loop traversal method to the table in tr
for (var rowindex = 0; rowindex < mailArr.length; rowindex++) {
//var tr = tab.insertRow(-1);//-1 refers to the last line
var tr = tab.insertRow(tab.rows.length - 1);//Insert into the last two lines, and the last line should be kept for the line that is selected all.
var td1 = tr.insertCell(-1);
td1.innerHTML = "<input type='checkbox'/>";
var td2 = tr.insertCell(-1);
td2.innerHTML = mailArr[rowindex].title;
var td3 = tr.insertCell(-1);
td3.innerHTML = mailArr[rowindex].name;
var td4 = tr.insertCell(-1);
td4.innerHTML = mailArr[rowindex].date;
}
}
//To make the Select All button take effect, you need to traverse all the rows of the table
function seleAll(mailTab, isSel) {
for (var i = 0; i < mailTab.rows.length; i++) {
var tr = mailTab.rows[i];
tr.cells[0].childNodes[0].checked = isSel;
}
}
</script>
</head>
<body>
<table id="tb" style="border-collapse: collapse;">
<tr>
<th>Sequence</th>
<th>Title</th>
<th>Send mailer</th>
<th>Send time</th>
</tr>
<!-- Loop increase-->
<!-- Select all-->
<tr>
<td colspan="4">
<input id="selA" type="checkbox" /><label for="selA">Select all</label>
<a href="#" id="delSel">Delete</a></td>
</tr>
</table>
</body>
</html>