为什么把循环放入一个函数中,人然后调用没有效果,只有声明一个对象在调用才有效果
来源:7-2 编程练习
lhebe
2019-04-16 11:00:49
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
}
div:not(:nth-of-type(2)) {
width: 500px;
height: 100%;
background-color: #00c4ff7a;
margin: 0 auto;
}
/*ul默认有外边距*/
ul {
width: 300px;
height: 100%;
background-color: #f9c3e6d6;
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">
//此处填写代码
(function(){
var li=document.getElementsByTagName('li');
var btnAdd=document.getElementById('btnAdd');
var btnRemove=document.getElementById('btnRemove');
var ul=document.getElementById('list');
btnAdd.onclick=function(){
// var i=ul.childNodes.length;childNodes是获取所有节点包括文本节点
var txt=document.createTextNode('我是li'+(li.length+1));
var newli=document.createElement('li');
newli.appendChild(txt);
ul.appendChild(newli);
if(li.length<=3){
d.f();
}
}
btnRemove.onclick=function(){
var i=ul.childElementCount;
if(i==0) return;
ul.removeChild(li[i-1]);
}
//var newli=[];
function A(){
this.f=function(){
for(var j=0;j<li.length;j++){
li[j].onmouseover=function(){
this.style.backgroundColor='blue';
}
li[j].onmouseout=function(){
this.style.backgroundColor='purple';
}
}
}
}
var d=new A();
d.f();
})()
</script>
</body>
</html>
1回答
好帮手慕星星
2019-04-16
同学你好,代码实现效果没有问题。
封装的函数中不需要声明对象,直接调用即可,如下:
可以重新测试下,祝学习愉快!
相似问题