<div>
<label for="">姓名:</label>
<input type="text" id="thename">
<label for="">年龄</label>
<input type="text" id="theage">
<label for="">学期</label>
<select name="" id="thexue">
<option value="p1">p1</option>
<option value="p2">p2</option>
<option value="p3">p3</option>
<option value="p4">p4</option>
<option value="p5">p5</option>
<option value="p6">p6</option>
</select>
<button onclick="addFun()">添加</button>
<button onclick="openFun()" id="acolor">开启隔行变色</button>
</div>
<table border="1" cellpadding=0 cellspacing=0>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>学期</th>
<th>操作</th>
</tr>
</thead>
<tbody id="thebody">
<!-- <tr οnmοuseοver="bcolor()">
<td>1</td>
<td>赵凌雪</td>
<td>20</td>
<td>P2</td>
<td><button οnclick="delFun(${item.id})">删除</button></td>
</tr> -->
</tbody>
</table>
var thename=document.getElementById("thename")
var thegae=document.getElementById("theage")
var thexue=document.getElementById("thexue")
var thebody=document.getElementById("thebody")
var acolor=document.getElementById("acolor")
var arr = [
{
id:1,name:'liujie',age:32,xue:'p2'},
{
id:2,name:'liujie1',age:32,xue:'p3'},
{
id:3,name:'liujie2',age:32,xue:'p4'}
]
getlou()
showFun()
function showFun(){
thebody.innerHTML=""
var lss=""
arr.forEach(function(item,index){
lss+=`<tr οnmοuseοver="bcolor()">
<td>${
index+1}</td>
<td>${
item.name}</td>
<td>${
item.age}</td>
<td>${
item.xue}</td>
<td><button οnclick="delFun(${
item.id})">删除</button></td>
</tr>
`
})
thebody.innerHTML=lss
}
//添加
function addFun(){
if(thename.value==""&&theage.value==""){
alert("名字跟年龄不能是空")
return
}
var obj={
}
obj.id=new Date().getTime()
obj.name=thename.value
obj.age=theage.value
obj.xue=thexue.value
arr.push(obj)
showFun()
setlou(arr)
}
//删除
function delFun(id){
arr.forEach(function(item,index){
if(id==item.id){
arr.splice(index,1)
}
})
showFun()
setlou(arr)
}
//隔行换色
var sure=true
function openFun(){
var trs=document.querySelectorAll("tbody>tr")
if(sure){
for(let i=0;i<trs.length;i++){
if(i%2==0){
acolor.innerHTML="关闭隔行换色"
trs[i].style.background="orange"
}else{
trs[i].style.background="green"
}
}sure=false
}else{
for(let j=0;j<trs.length;j++){
acolor.innerHTML="开启隔行变色"
trs[j].removeAttribute("style")
sure=true
}
}
}
//存
function setlou(arr){
localStorage.setItem("myarr",JSON.stringify(arr))
}
//取
function getlou(){
var str=localStorage.getItem("myarr")
if(str==null){
arr=[]
return
}
arr=JSON.parse(str)
}