麻烦老师帮忙检查一下代码
来源:11-2 编程练习
程序员小张
2020-05-03 11:00:26
<!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">
var lis = document.querySelectorAll("li");
for(var i = 0;i < lis.length;i++){
lis[i].onmousemove = function(){
this.style.backgroundColor = "blue";
}
lis[i].onmouseout = function(){
this.style.backgroundColor = "#cdffc0";
}
}
var add = document.getElementById("btnAdd");
var del = document.getElementById("btnRemove");
var ul = document.getElementById("list");
var num = 4;
add.onclick = function(){
var li = document.createElement("li");
var txt = document.createTextNode("我是li" + num);
num++;
li.appendChild(txt);
ul.appendChild(li);
}
del.onclick = function(){
var last = ul.lastChild;
while(!(last.innerHTML)){
last = last.previousSibling;
}
ul.removeChild(last);
}
</script>
</body>
</html>
1回答
好帮手慕码
2020-05-05
同学你好,代码中的问题:
1、当点击删除元素全部把li元素删除之后,继续点击按钮,会出现报错:
是因为没有子元素了,继续移除就会出错,可以提前添加判断,如下:
2、删除添加之后,li的顺序有误。建议修改如下:
如果我的回答帮到了你,欢迎采纳,祝学习愉快~
相似问题