🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
> 效果如图 ![](https://box.kancloud.cn/c83b3ebbf5e9090eca263ebf57bc7707_595x725.gif) > html代码 ``` <input type="text" id="shop"> <input type="text" id="phone"> <button id="add">添加</button> <table id="table"> <thead> <tr><th>商城</th><th>手机</th></tr> </thead> <tbody> <tr><td>天猫</td><td>小米</td></tr> <tr><td>天猫</td><td>小米</td></tr> <tr><td>天猫</td><td>小米</td></tr> <tr><td>天猫</td><td>小米</td></tr> </tbody> </table> ``` > js代码 ``` window.onload = ()=>{ var table = document.getElementById("table"); var shop = document.getElementById("shop"); var phone = document.getElementById("phone"); var add = document.getElementById("add"); var rows = table.tBodies[0].rows; //获得当前的rows,此时是类数组对象 var rows_arr = Array.prototype.slice.call(rows); //将现在的rows转换为array console.log(rows_arr); //tr tr tr tr rows_arr.forEach((element, index)=>{ if(index%2 == 0) { element.style.backgroundColor = "pink"; }else { element.style.backgroundColor = "aqua"; } }) add.onclick = ()=>{ var shopValue = shop.value; var phoneValue = phone.value; var tr = document.createElement("tr"); var td1 = document.createElement("td"); var td2 = document.createElement("td"); td1.append(shopValue); td2.append(phoneValue); tr.append(td1, td2); table.tBodies[0].append(tr); var rows_arr2 = Array.prototype.slice.call(rows); //将现在的rows数量转换为array // console.log(rows_arr2);//tr tr tr tr tr rows_arr2.forEach((element, index)=>{ if(index%2 == 0) { element.style.backgroundColor = "pink"; }else { element.style.backgroundColor = "aqua"; } }) } } ```