为什么我新建的li不能实现移入效果?HTMLCollection不是动态的吗?
来源:7-2 编程练习
PHXL
2019-08-15 20:09:56
<!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="list">
<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 list=document.querySelector("ul#list");
var items=list.getElementsByTagName("li");
for(var i=0;i<items.length;i++){
items[i].onmouseover=function(){
this.style.backgroundColor="#00f";
};
items[i].onmouseout=function(){
this.style.backgroundColor="#ffad86";
};
}
var btnAdd=document.getElementById("btnAdd");
var count=4;
btnAdd.onclick=function(){
var newItem=document.createElement("li");
newItem.innerHTML="我是li"+count;
count++;
list.appendChild(newItem);
};
var btnRemove=document.getElementById("btnRemove");
btnRemove.onclick=function(){
if(list.lastElementChild){
list.removeChild(list.lastElementChild);
}
};
</script>
</body>
</html>
1回答
你好同学,这个和HTMLCollection概念没有什么关系,是因为代码执行问题。代码顺序执行完毕之后就不会再次执行了。参考如下理解
所以想要新添加的li有移入效果,需要在点击事件中加入事件,如下:
祝学习愉快,望采纳。
相似问题