为什么删除函数无法执行呢

来源:7-2 编程练习

Aries典

2018-12-07 11:53:26

<!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: #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;
    }

    li:hover {
        background-color: pink;
    }
    </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 btnAdd = document.getElementById('btnAdd'),
        btnRemove = document.getElementById('btnRemove'),
        li = document.getElementsByTagName('li');
    ul = document.getElementById('list');
    //添加节点
    btnAdd.onclick = function() {
        len=li.length;
        var li1 = document.createElement('li'),
            tex = document.createTextNode('我是li'+(len+1));
        li1.appendChild(tex);
        ul.appendChild(li1);
        
    }
    //删除节点
    btnRemove.onclick=function(){
    	ul.removeChild(li.lastElementChild);
    }
    for (var i = 0; i < li.length; i++) {
        li[i].onmouseover = function() {
            this.style.backgroundColor = 'pink';
        };
        li[i].onmouseout = function() {
            this.style.backgroundColor = 'red';
        }
    }
    </script>
</body>

</html>


写回答

1回答

好帮手慕星星

2018-12-07

鼠标移除的应该是ul的最后的一个子元素,不是li的子元素哦,如下是代码中的问题:

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

可以在代码中添加如果ul的子元素长度为0,就return返回,否则继续移除会报错的。

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

移入列表改变颜色还是有问题的,不论是原有的前三个列表,还是删除之后新增加的前三个列表,鼠标移入的时候都会改变颜色,其他列表是不改变颜色的,自己可以完善下。

祝学习愉快!

0

0 学习 · 4826 问题

查看课程