js 添加表格元素,隔行换色,删除操作:
HTML部分代码:
<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="buttonOne">删除</button></td> </tr> </tbody> </table> </div> <button id="buttonTwo">添加</button>
JS部分代码:
let th = document.getElementsByTagName('thead')[0]; //获取thead标签 let tbody = document.getElementsByTagName('tbody')[0]; //获取tbody标签 let but = document.getElementById('buttonTwo'); //获取button标签 let content = 100; but.onclick = function(){ let theadtr = th.getElementsByTagName('tr')[0]; let ths = theadtr.children; //获取tr中th的数量 let newtr = document.createElement('tr'); //创建一个 tr 标签 for(let i = 0 ; i < ths.length;i++){ let newtd = document.createElement('td'); //创建 td 标签 let tbodytr = tbody.children; // 获取tbody中的子元素 if(i == 0){ newtd.innerHTML = tbodytr.length + 1; //数值+1 } if(i == 1){ newtd.innerHTML = content; content += 100; } if(i == ths.length-1){ newtd.innerHTML = '<button>删除</button>' } newtr.appendChild(newtd); //将td加入到tr中 } tbody.appendChild(newtr); color() } //换色 function color(){ let trs = tbody.children; for(let i = 0 ; i < trs.length ; i++ ){ if(i % 2 == 1){ trs[i].style.backgroundColor = "pink"; }else{ trs[i].style.backgroundColor = "white"; } } } //删除 tbody.addEventListener('click',function(e){ e = e || window.event; let targetElement = e.target || e.srcElement; if(targetElement.innerHTML == "删除"){ //触发”删除“事件 let istr = targetElement.parentElement.parentElement; tbody.removeChild(istr); color(); issort(); } }) //排序 function issort(){ let num = tbody.children; for(let i = 0 ; i < num.length ; i++){ let nums = num[i].children[0]; nums.innerHTML = i+1; } }