7-2,练习

来源:7-2 编程练习

qq_紾悕_1

2019-07-01 18:27:11

<!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 ul = document.getElementById("list");
    var li = ul.getElementsByTagName('li');
    var btnAdd = document.getElementById("btnAdd");
    var btnRemove=document.getElementById("btnRemove");
    //for循环 绑定鼠标事件,
    for (var i=0; i<li.length;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 txt = document.createTextNode("我是li"+(++i));
        newLi.appendChild(txt);
        ul.appendChild(newLi);
    };
    btnRemove.onclick = function(){
        if(li.length>0){
            ul.removeChild(ul.lastElementChild);
        };
    }
    </script>
</body>

</html>


写回答

1回答

好帮手慕夭夭

2019-07-01

你好同学,当添加很多元素删除之后再重新添加之后,索引不对,如下

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

这是因为点击事件中并没有重新获取li的长度,建议如下修改:

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

祝学习愉快,望采纳。

1

0 学习 · 4826 问题

查看课程

相似问题