麻烦老师帮忙检查一下

来源:11-2 编程练习

木子小可爱

2019-09-09 20:15:39

<!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.getElementById('list');
    var li=document.getElementsByTagName('li');
    var btnAdd=document.getElementById('btnAdd');
    var btnRemove=document.getElementById('btnRemove');
    for(var i=0,len=li.length;i<len;i++){
        li[i].onmouseover=function(){
            this.style.backgroundColor='blue';
        }
        li[i].onmouseout = function(){
            this.style.backgroundColor='orange';
        }
    }
    btnAdd.onclick=function(){
        var newLi=document.createElement('li');
        var text=document.createTextNode("我是li"+(li.length+1));
        newLi.appendChild(text);
        lis.appendChild(newLi);
    }
    btnRemove.onclick=function(){
        lis.removeChild(lis.lastElementChild);
    }


    //此处填写代码
    </script>
</body>

</html>

写回答

1回答

好帮手慕糖

2019-09-10

同学你好,1、当点击删除元素全部把li元素删除之后,继续点击按钮,是因为没有子元素了,继续移除就会出错,可以提前添加判断,如下:


http://img1.sycdn.imooc.com/climg/5d7708160001624206730224.jpg

2、当把开始3个li元素删除之后,点击添加按钮添加li元素,鼠标移入前三个的li的时候没有改变背景颜色。可以把改变颜色的代码封装起来,对长度进行判断,然后调用;可以参考如下:

http://img1.sycdn.imooc.com/climg/5d77097809cfc79110850768.jpg

希望能帮助到你,欢迎采纳。

祝学习愉快!

0

0 学习 · 40143 问题

查看课程