this.style.background="purple";的this换成li[i]为什么就不行了
<!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 lit=document.getElementById("list"),
li=lit.children,
bta=document.getElementById("btnAdd"),
btr=document.getElementById("btnRemove");
// li[1].style.background="purple";
for(var i=0;i<li.length;i++){
li[i].onmouseover=function(){
this.style.background="purple";
}
li[i].onmouseout=function(){
this.style.background="pink";
}
}
bta.onclick=function(){
var nli=document.createElement("li"),
ntxt=document.createTextNode("我是li"+(li.length+1));
nli.appendChild(ntxt);
lit.appendChild(nli);
}
btr.onclick=function(){
lit.removeChild(lit.lastElementChild);
}
</script>
</body>
</html>
正在回答
同学你好,for循环是在触发移入移出事件之前就执行完了,在移入移出事件里面打印i值,是循环之后的值,也就是3,可以打印看下:
控制台:
页面中并没有索引为3的li 元素,所以会报错。同学可以再理解下。祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星