老师帮忙看看

来源:11-2 编程练习

慕仙9874720

2019-12-02 20:58:50

<!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 list=document.getElementById("list"),

    arryli=list.querySelectorAll("li"),

        btnAdd=document.getElementById("btnAdd"),

        btnRemove=document.getElementById("btnRemove");

    for(var i=0,len=arryli.length;i<len;i++){

        arryli[i].onmouseover=function(){

    this.style.backgroundColor="blue";

    }

        arryli[i].onmouseout=function(){

            this.style.backgroundColor="orange";

        }

    }


    btnAdd.onclick=function(){

        var licount=document.getElementsByTagName("li"),

            newli=document.createElement("li"),

            text=document.createTextNode("我是li"+(licount.length+1));

        newli.appendChild(text);

        list.appendChild(newli);


    }

    btnRemove.onclick=function(){

        list.removeChild(list.lastElementChild);

    }

    </script>

</body>


</html>


写回答

1回答

好帮手慕星星

2019-12-03

同学你好,代码中问题如下:

1、当把li全部删除之后继续点击删除按钮,会报错:



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

因为已经没有子元素了,继续移除就会报错。可以添加一个判断,参考:

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

2、将原有的li移除之后,点击添加元素按钮,新添加的li(前三个)移入没有改变背景颜色。因为

querySelectorAll方法获取的是元素静态集合,元素改变之后不能跟着改变。可以将改变样式的代码封装起来调用,参考:

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

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

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

0

0 学习 · 40143 问题

查看课程