表格的跨行换色主要用到了JS的函数以及for循环,今天以表格的增加,删除,隔行换色来给大家演示一下。
<body>
<div>
<table border="1px" id="tabled">
<thead>
<tr>
<td>序号</td>
<td>内容</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>DATA</td>
<td><button id="button_One">删除</button></td>
</tr>
</tbody>
</table>
</div>
<button id="button_Two">添加</button>
</body>
<script>
let thead_thead = document.getElementsByTagName('thead')[0]; //获取thead
let tbody = document.getElementsByTagName('tbody')[0]; //获取tbody
let but = document.getElementById('button_Two'); //获取‘添加’按钮
let content = 100; //设定初始内容框为100
//绑定一个函数
but.onclick = function() {
let thead_tr = thead_thead.getElementsByTagName('tr')[0]; //获取tr
let thsss = thead_tr.children; //获取tr中得子元素
let new_tr = document.createElement('tr'); //新建一个tr
//利用for循环添加每个单元格得内容
for (let i = 0; i < thsss.length; i++) {
let new_td = document.createElement('td'); //新建一个td
let tbody_tr = tbody.children; //获取tbody得子元素
if (i == 0) {
new_td.innerHTML = tbody_tr.length + 1;
}
if (i == 1) {
new_td.innerHTML = content; //新的td会+100
content += 100;
}
if (i == thsss.length - 1) {
new_td.innerHTML = '<button>删除</button>'
}
new_tr.appendChild(new_td); //将新建的单元格输入到新的tr中
}
tbody.appendChild(new_tr); //将新建的tr输入到tbody中完成添加
color();
}
function color() {
let tr_s = tbody.children; //获取tbody的子元素
//利用for循环更改序号的值 以及颜色
for (let i = 0; i < tr_s.length; i++) {
tr_s[i].children[0].innerHTML = i + 1;
if (i % 2 == 0) { //区分单数行和双数行
tr_s[i].style.backgroundColor = "";
} else{
tr_s[i].style.backgroundColor = "blue";
}
}
}
tbody.addEventListener('click', function(sr) {
sr = sr || window.event;
let targetElement = sr.target || sr.srcElement;
if (targetElement.innerHTML == "删除") {
let capture = targetElement.parentElement.parentElement; //获取得到的元素,寻找其父级的父级,在这时指的是tr
tbody.removeChild(capture); //进行删除
color();
}
}
)
</script>
下面是效果:
谢谢大家观看,欢迎评论区讨论。