麻烦老师帮忙检查一下代码,谢谢~
来源:11-2 编程练习
慕粉2243585596
2020-05-20 22:39:09
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> html, body { margin: 0; padding: 0; } div:not(:nth-of-type(2)) { width: 500px; height: 100%; background-color: #a0e4ff; margin: 0 auto; } /*ul默认有外边距*/ ul { width: 300px; height: 100%; background-color: #ecc7ea; list-style: none; /*清除默认边距*/ margin: 0; padding: 0; margin: 20px auto; margin-bottom: 30px; } li { width: 200px; height: 30px; line-height: 30px; margin: 30px auto; background-color: #cdffc0; } </style> </head> <body> <div id="box"> <button id="btnAdd">添加元素</button> <button id="btnRemove">删除元素</button> <ul id="list">我是ul <li>我是li1</li> <li>我是li2</li> <li>我是li3</li> </ul> </div> <script type="text/javascript"> //此处填写代码 //获取所有li元素 var li=document.getElementById("list").querySelectorAll("li"), ul=document.getElementById("list"), addbtn=document.getElementById("btnAdd"), delbtn=document.getElementById("btnRemove"),j=li.length; for(var i=0;i<j;i++){ li[i].onmouseover=function(){ this.style.background="yellow"; } li[i].onmouseout=function(){ this.style.background="red"; } } addbtn.onclick=function(){ var newli=document.createElement("li"); var newtext=document.createTextNode("我是li"+(i+1)); newli.appendChild(newtext); ul.appendChild(newli); //我觉得下边这种更方便 /*ul.innerHTML+="<li>我是li"+(i+1)+"</li>";*/ i++; } delbtn.onclick=function(){ if(i>0){ //返回最后一个节点 var lastli=document.querySelector("li:last-child"); //删除最后一个节点 ul.removeChild(lastli); i--; } } </script> </body> </html>
1回答
好帮手慕言
2020-05-21
同学你好,效果是正确的。另外:代码具有灵活性,使用同学注释的代码也是可以实现效果的。
祝学习愉快~
相似问题