【HTML+CSS+JavaScript】实现待办事项(纯DOM实现)

需求:实现待办事项

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>todoList</title>
    <style>    
        #todoList {
            list-style: none;
            margin:10px 0px;
            padding:0;
            600px;
        }
        #todoList li {
            margin-bottom:5px;
            padding: 10px;
            border: 1px solid #ccc;
            background:#f5f5f5;
            position: relative;
        }
        input {
            padding:10px;
            font-size:16px;
            border:1px solid #ccc;
        }
        button {
            padding:10px 20px;
            border:1px solid #ccc;
            background: #f5f5f5;
            outline: none;
            cursor: pointer;
        }

        #todoList span {
            position: absolute;
            right: 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <input type="text" id="content"> 
    <button id="btn">添加</button>
    <ul id="todoList">
        <li>取钓鱼 <span>&times;</span></li>
        <li>取洗澡 <span>&times;</span></li>
        <li>取吃饭 <span>&times;</span></li>
        <li>去睡觉 <span>&times;</span></li>
    </ul>


    <script>    
        var input = document.querySelector('#content');
        var btn = document.querySelector('#btn');
        var todoList= document.querySelector('#todoList');
        var spans = document.querySelectorAll('#todoList span');


        btn.onclick = function(){
            //获取 input的内置
            var text = input.value;

            //创建li元素 并给li元素添加包裹 内容
            var li = document.createElement('li');
            li.innerText = text;
            var span = document.createElement('span');
            span.innerHTML = '&times;';
            li.appendChild(span);

            //把li元素添加到ul中
            todoList.appendChild(li);
        }    


        /*spans.forEach(function(span){
            span.onclick = function(){
                todoList.removeChild(this.parentNode)
            }
        })*/

        //委派方式绑定
        todoList.onclick = function(event) {
            if (event.target.nodeName === 'SPAN') {
                this.removeChild(event.target.parentNode);
            }
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/neymargoal/p/9475351.html