js实现todolist总结

首先在网页布局设置好的情况下,进行js文件的编写,要求实现增加,删除,和实时变化,其实这都可以在存在浏览器的本地存储中。下面先列出我的html页面及css文件内容

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>表</title>
    <link rel="stylesheet" href="./css/todoList.css">
</head>
<body>
<header>
    <p>ToDoList</p>
    <form action="" name="myform">
        <input name="content" value = "" class="input_text" type="text" placeholder="请输入待办事项" required>
        <input name = "" class="submit_button" type="submit" value = "提交">
    </form>
</header>
<main>
    <ul class="tab">
        <li type ="all" class = "hot">全部任务</li>
        <li type = "left">未完成</li>
        <li type = "done">已完成</li>
        <div class = "top1"></div>
    </ul>
    <ul class="content">

    </ul>

</main>
<script src = './js/todoList.js'></script>
</body>
</html>
*{
    margin:0;
    padding:0;
    list-style:none;
}
header{
    height: 80px;
    width: 1200px;
    position: relative;
    right: 0;
    left: 0;
    margin: auto;
    border-bottom: 1px solid #666666;
}
header p{
    position: absolute;

    right: 0;
    left: 0;
    margin: auto;
    text-align: center;
}
.tab{
    width: 600px;
    display: flex;
    justify-content: space-between;
    text-align: center;
    align-items: center;
    height: 20px;
    position: absolute;
    top: 100px;
    right: 0;
    left: 0;
    margin: auto;
}
.tab li{
    width: 200px;
    font-size: 20px;
    height: 20px;
    padding: 10px;
}
.hot{
    color: #FFFFFF;
    transition: all 1s;
}
li.hot:nth-child(1)~ .top1{
    transform: translate(0,0);
}
li.hot:nth-child(2)~ .top1{
    transform: translate(100%,0);
}
li.hot:nth-child(3)~ .top1{
    transform: translate(200%,0);
}
.top1{
    width: 200px;
    height: 30px;
    position: absolute;
    border-radius: 10px;
    top: 0;
    left: 0;
    z-index: -1;
    background: #34aadc;
    transition: all ease-in 0.5s;
}
.content{
    width: 600px;
    flex-direction: column;
    height: auto;
    position: absolute;
    top: 130px;
    right: 0;
    left: 0;
    margin: auto;
}
.content li{
    padding: 10px;
}
.content p{
    display: inline-block;
}
.content time{
    float: right;
}
.content del{
    margin-left: 20px;
    float: right;
    text-decoration: none;
}
.content del:hover{
    cursor: pointer;
}

form{
    position: relative;
    top: 30px;
    right: 0;
    left: 0;
    margin: auto;
    text-align: center;
}

.input_text{
    width: 400px;
    height: 36px;
    padding: 0 0 0 10px;
    outline: none;
}
.submit_button{
    height: 40px;
    width: 80px;
    background: transparent;
    border: 1px solid #666666;
    outline: none;
}

大家可以看到我这里定义了一个页面内并没有的类,这是为了在后面通过js进行添加删除的操作,实现页面内样式的变换

首先获取顶部标题

let title = document.querySelectorAll('.tab>li');

 然后添加删除和增加hot类的事件

title.forEach((ele,index) => {
        ele.onclick = function () {
            title[prev].classList.remove('hot');
            this.classList.add('hot');
            prev = index;
        }
    });

接下来,进行js文件的编写

首先,添加事件

window.addEventListener('load',function () {})

然后获取页面的内元素,我们先进行页面内列表的实时变化,也就是对勾选框添加事件,

1.获取页面元素,并定义要显示的列表


    let contents = document.querySelector('.content');

    let prev =0;
    


//这里添加的是要显示到页面内的列表元素
    let todolist =[
        {
            id:1, content:'放假好好睡一觉',ctime:'2019.06.08',status:false
        },
        {
            id:2, content:'放假好好睡两觉',ctime:'2019.06.09',status:false
        },
        {
            id:3, content:'不睡觉',ctime:'2019.06.07',status:true
        },
        {
            id:4, content:'学习',ctime:'2019.06.06',status:true
        }

    ];

2.因为我们网页上有三个分类,分别为所有(all),未完成(left),和已完成(done),所以我们要进行元素的筛选,即在点击各个标题时,进行数据的筛选,这里我们用各类的type作为筛选的 标准

所以在标题点击的事件title.onclick中增加type的定义

            type = this.getAttribute('type');

首先定义一个filterdata函数,对传进去的列表进行筛选,并返回数据

 function  filterdata(type){
        let arr = [];
        switch(type){
            case 'all':
                arr = todolist;
                break;
            case 'done':
                arr = todolist.filter(function (ele) {return ele.status});
                break;
            case 'left':
                arr = todolist.filter(function (ele) {return !ele.status});
                break;
        }

        return arr;
    }

3.然后我们要对筛选出来的数据进行‘渲染’操作,

这里我们需要定义一个 render函数,通过status不同对勾选框进行不同的定义

 function render(arr) {
        let html = '';
        arr.forEach(function (elem) {
            if(elem.status){
                html +=`
                    <li>
                        <input type="checkbox" checked> <p>${elem.content}</p> <del>X</del> <time>${elem.ctime}</time>
                    </li>
                `;
            }else{
                html +=`
                <li>
                    <input type="checkbox" > <p>${elem.content}</p> <del>X</del> <time>${elem.ctime}</time>
                </li>
                `;
            }
        });

        contents.innerHTML = html;
    }

到这里我们就实现了页面内,通过点击标题,显示不同的待办事项,即分出未完成和完成的列表。

接下来就是对页面勾选和删除状态进行实时的渲染

我们对列表内容增加一个点击事件,

contents.onclick = function(e){
    let target = e.target;
    let arr = todolist;
    let id = target.parentNode.id;
    if (target.nodeName === "INPUT") {
        let a = arr.filter(ele=>ele.id == id)[0];
        a.status=target.checked;
    } else if (target.nodeName === "DEL") {
        let index = arr.findIndex(ele => ele.id == id);
        arr.splice(index, 1);
    }
    render(filterdata(type));
 };

 这段函数就是当列表内容点击时,判断点击的是勾选框还是删除,如果是勾选框,选出相应的id对应的内容,并修改其status状态,如果是del,则对该条内容进行删除操作。,最后别忘了对新的列表进行筛选显示

还要对渲染列表中的li增加一个id属性

function render(arr) {
        let html = '';
        arr.forEach(function (elem) {
            if(elem.status){
                html +=`
                    <li id = ${elem.id}>  //这里增加了id属性
                        <input type="checkbox" checked> <p>${elem.content}</p> <del>X</del> <time>${elem.ctime}</time>
                    </li>
                `;
            }else{
                html +=`
                <li id = ${elem.id}>      //这里增加了id属性
                    <input type="checkbox" > <p>${elem.content}</p> <del>X</del> <time>${elem.ctime}</time>
                </li>
                `;
            }
        });

        contents.innerHTML = html;
    }

4.接下来就是增加操作,先进行增加函数的编写

function createObj(){
        let id = todolist[todolist.length-1].id+1;
        let content = input_content.value;
        let ctime = new Date().toLocaleDateString();
        let status = false;
        return {id,content,ctime,status};
    }

定义新增加的各个元素,并返回相应的值。

然后给提交按钮增加点击事件,并去掉默认行为,增加之后别忘了‘渲染一下’

 let forms = document.forms[0];
    let input_content = forms.elements['content'];
    let input_submit = forms.elements[1];

    input_submit.onclick = function(e){
        e.preventDefault();
        let obj = createObj();
        todolist.push(obj);
        forms.reset();
        render(filterdata(type));
    };

5.接下来就是最后一步,把增加,删除,实时状态的改变,存储到本地数据中

先编写一个存储函数,把todolist转为字符串后存入本地数据中

  function saveData() {
        localStorage.setItem('todolist',JSON.stringify(todolist))
    }

然后需要对todolist进行初始化一下

let str = localStorage.getItem('todolist');
    if(!str){
        saveData();
        str = localStorage.getItem('todolist');
    }
    todolist = JSON.parse(str);

到此,整个todolist的增删改还有存储都完成了,最后对整体的js进行查漏补缺 整理如下

window.addEventListener('load',function () {
    let title = document.querySelectorAll('.tab>li');
    let contents = document.querySelector('.content');

    let prev =0;
    let todolist =[
        {
            id:1, content:'放假好好睡一觉',ctime:'2019.06.08',status:false
        },
        {
            id:2, content:'放假好好睡两觉',ctime:'2019.06.09',status:false
        },
        {
            id:3, content:'不睡觉',ctime:'2019.06.07',status:true
        },
        {
            id:4, content:'学习',ctime:'2019.06.06',status:true
        }

    ];


    let str = localStorage.getItem('todolist');
    if(!str){
        saveData();
        str = localStorage.getItem('todolist');
    }
    todolist = JSON.parse(str);

    title.forEach((ele,index) => {
        ele.onclick = function () {
            title[prev].classList.remove('hot');
            this.classList.add('hot');
            prev = index;
            type = this.getAttribute('type');

            render(filterdata(type));
        }
    });


    title[0].onclick();



    function  filterdata(type){
        let arr = [];
        switch(type){
            case 'all':
                arr = todolist;
                break;
            case 'done':
                arr = todolist.filter(function (ele) {return ele.status});
                break;
            case 'left':
                arr = todolist.filter(function (ele) {return !ele.status});
                break;
        }

        return arr;
    }
    //////////////////////////添加///////////////////////////////////
    let forms = document.forms[0];
    let input_content = forms.elements['content'];
    let input_submit = forms.elements[1];

    input_submit.onclick = function(e){
        e.preventDefault();
        let obj = createObj();
        todolist.push(obj);
        forms.reset();
        render(filterdata(type));
        saveData();
    };
    ///////////////////////////saveDATA////////////////////////////////////
    function saveData() {
        localStorage.setItem('todolist',JSON.stringify(todolist))
    }




    function createObj(){
        let id = todolist[todolist.length-1].id+1;
        let content = input_content.value;
        let ctime = new Date().toLocaleDateString();
        let status = false;
        return {id,content,ctime,status};
    }
    ///////////////////修改状态///////////////////////////////////
    /*
        视图->数据
        li ->数组元素
        复选框 ->数组元素status (li->id)

     */
contents.onclick = function(e){
    let target = e.target;
    let arr = todolist;
    let id = target.parentNode.id;
    if (target.nodeName === "INPUT") {
        let a = arr.filter(ele=>ele.id == id)[0];
        a.status=target.checked;
    } else if (target.nodeName === "DEL") {
        let index = arr.findIndex(ele => ele.id == id);
        arr.splice(index, 1);
    }
    saveData();
    render(filterdata(type));
 };


    /////////////////渲染/////////////////////////////

    function render(arr) {
        let html = '';
        arr.forEach(function (elem) {
            if(elem.status){
                html +=`
                    <li id = ${elem.id}>
                        <input type="checkbox" checked> <p>${elem.content}</p> <del>X</del> <time>${elem.ctime}</time>
                    </li>
                `;
            }else{
                html +=`
                <li id = ${elem.id}>
                    <input type="checkbox" > <p>${elem.content}</p> <del>X</del> <time>${elem.ctime}</time>
                </li>
                `;
            }
        });

        contents.innerHTML = html;
    }
})
发布了16 篇原创文章 · 获赞 11 · 访问量 5739

猜你喜欢

转载自blog.csdn.net/Cirzearchenille/article/details/91046280