【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;
            width: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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM