请帮忙检查一下,谢谢

来源:11-2 编程练习

谁说绿萝不开花

2019-12-09 09:53:15

<!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 addBtn = document.getElementById('btnAdd');

     var removeBtn = document.getElementById('btnRemove');

     var list = document.getElementById('list');

     var lis = list.getElementsByTagName('li');

     for(var i=0;i<lis.length;i++){

         lis[i].onmouseover = function(){

             this.style.backgroundColor = 'blue';

         }

         lis[i].onmouseout = function(){

             this.style.backgroundColor = 'red';

     }

     }

     

     addBtn.onclick = function(){

         var len = list.children.length+1;

         var newLi = document.createElement('li');

         var newText = document.createTextNode('我是li'+len);

         newLi.appendChild(newText);

         list.appendChild(newLi);

     }

     removeBtn.onclick = function(){

         list.removeChild(list.lastChild);

     }

    </script>

</body>


</html>


写回答

1回答

好帮手慕慕子

2019-12-09

同学你好,对于你代码中存在的问题,解答如下:

  1. 当点击删除元素全部把li元素删除之后,继续点击按钮,会出现报错。如下:

    http://img.mukewang.com/climg/5dedb85309f8b0ec19120172.jpg

    是因为没有子元素了,继续移除就会出错,可以提前添加判断,如下:

    http://img.mukewang.com/climg/5dedb888099fefb806220247.jpg

  2. 当把所有li元素删除之后,点击添加按钮添加li元素,鼠标移入li的时候没有改变背景颜色。可以把改变颜色的代码封装起来,然后在调用,参考:

    http://img.mukewang.com/climg/5dedb8df098d823808230551.jpg

如果帮助到了你,欢迎采纳,祝学习愉快~

0

0 学习 · 40143 问题

查看课程