在javascript中构建待办事项列表

时间:2016-09-01 22:07:02

标签: javascript html

我对javascript很新,并且通过javascript& jquery书。为了测试自己,我正在尝试构建一个todo列表javascript。在本书的帮助下,我已经能够构建从列表中删除功能。但是,我似乎无法使addToList功能正常工作,我也不知道为什么。洞察力非常受欢迎。

var item, list, feedback;
item = document.getElementById("item");
list = document.getElementById("list");
feedback = document.getElementById("feedback");

function addToList() { 

    console.log("I am in");
    var newElement = document.createElement("li");
    console.log(item.value);
    newItem = item.value
    newElement.innerHTML = newItem;
    list.appendChild('<a>newElement</a>');
    // el.innerHTML = item.value;
    feedback.innerHTML = "Item added.";
    console.log("working");
}

function removeFromList(e) {
    var target, elParent, elGrandparent;
    target = e.target;
    elParent = target.parentNode;
    elGrandparent = target.parentNode.parentNode;
    elGrandparent.removeChild(elParent);
    e.preventDefault();
    feedback.innerHTML = "Item removed.";
}

list.addEventListener("click", function (e) {
    removeFromList(e);
}, false);

var btn = document.getElementById("add");
btn.addEventListener("click", addToList, false);














<!DOCTYPE html>
<html>
    <head>
        <title>Todo List</title>
    </head>

    <body>
        <input type="text" name="item"><br />
        <input type="button" name="add" value="Add" id="add">

        <ul id="list">
            <li><a href="#">Go to the store.</a></li>
            <li><a href="#">Visit family.</a></li>
        </ul>

        <div id="feedback"></div>


        <script type="text/javascript" src="todo.js"></script>
    </body>
</html>

3 个答案:

答案 0 :(得分:0)

我在这里看到两个错误:

  • 您正试图以这种方式从JS获取item元素 item = document.getElementById("item");但您的HTML <input type="text"中没有item个ID,因此JS代码无法找到该元素。 您应该以这种方式修改HTML:

    <input type="text" id="item">

  • 您正在向appendChild方法 - list.appendChild('<a>newElement</a>');发送字符串,但它应接受指向DOM元素的链接。所以你可以用这样的方式重写它:

    var linkToElement = document.createElement("a"); linkToElement.appendChild(newElement); list.appendChild(linkToElement);

在此处查看详细信息http://jsbin.com/dowipuqayo/edit?html,js,output。这些变化只是你的代码。

答案 1 :(得分:0)

我已经完成了您的示例并修复了addToList() 代码被评论,所以它应该解释大部分正在发生的事情。

var item, list, feedback;
/*
* item will be null here becuase there is
* no value when the page first loads.
*/
//item = document.getElementById("item");

// these two are fine because they exist
list = document.getElementById("list");

feedback = document.getElementById("feedback");

function addToList() {
  // This is where we get the input value (within the funciton)
  item = document.getElementById("item");
  
  // We first create the <li> node
  var newElement = document.createElement("li");  
  // Now we create a text node
  var newItem = document.createTextNode(item.value);  
  // append the text node to the <li> node
  newElement.appendChild(newItem);
  
  // newElement is now ready to be appended to list
  list.appendChild(newElement);

  feedback.innerHTML = "Item added.";
}

function removeFromList(e) {
  e.remove();
}

list.addEventListener("click", function(e) {
  removeFromList(e.target);
}, false);

var btn = document.getElementById("add");
btn.addEventListener("click", addToList, false);
<input type="text" name="item" id="item"><br />
<input type="button" name="add" value="Add" id="add">

<ul id="list">
  <li><a href="#">Go to the store.</a></li>
  <li><a href="#">Visit family.</a></li>
</ul>

<div id="feedback"></div>

如果您对代码有任何疑问,请与我们联系。

答案 2 :(得分:0)

演示:https://javascripttodolist.web.app/

源代码:https://github.com/mhsunny/JavaScript-Todo-List-Project

JavaScript-Todo-List-Project

如何使用JavaScript构建待办事项列表应用

这是一个示例项目,说明如何使用具有JavaScript基本知识的Jaascript创建待办事项列表。您将找到如何使用过滤器功能,addEventListener和使用Modren es6 Arrow函数更改数组等。

app.js

# App.js file
<code>
<pre>
const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');
const message = document.querySelector('.message');
const searchForm = document.querySelector('.search');

const generateTemplate = todo =>{
    const html = `
        <li class="list-group-item d-flex justify-content-between align-items-center">
            <span>${todo}</span>
            <i class="far fa-trash-alt delete"></i>
        </li> 
    `;
    list.innerHTML += html; 
}

addForm.addEventListener('submit', e=>{
    e.preventDefault();
    const todo = addForm.add.value.trim();
    if(todo.length){
        message.classList.add('d-none');
        addForm.add.classList.add('class', 'success');
        generateTemplate(todo);
        addForm.reset();
        addForm.add.focus();
        message.textContent = 'Great! You added your todo item.';
        message.classList.remove('alert-danger');
        message.classList.add('alert-success');
    }else{
        message.classList.add('d-block');
        addForm.add.classList.add('class', 'error');
        message.textContent = 'Oops! Please enter your item.';
        message.classList.remove('alert-success');
        message.classList.add('alert-danger');

    }

});


//delete todo

list.addEventListener('click', e=>{

    if(e.target.classList.contains('delete')){
        e.target.parentElement.remove();
    }
})

const showTodoList = (searchText) =>{
    console.log(searchText)
    childsOfList= Array.from(list.children);

        Array.from(list.children)
        .filter(li =>{ 
             return !li.textContent.toLowerCase().includes(searchText)  
         }).forEach(li=>{
            li.classList.add('filtered')
        }) 

        Array.from(list.children)
        .filter(li =>{ 
             return li.textContent.toLowerCase().includes(searchText)  
         }).forEach(li=>{
            li.classList.remove('filtered')
        }) 

}


//keyup search
searchForm.search.addEventListener('keyup', e=>{
    e.preventDefault();
    const searchText = e.target.value.trim().toLowerCase();
     showTodoList(searchText);
})


</code>
</pre>


Index.html

<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
   <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
   <link rel="stylesheet" href="styles.css">
   <title>Javascript Todo List</title>
</head>
<body>
   <div class="container">
       <header class="text-center text-light my-4">
           <h1 class="mb-4">Todo List by Javascript</h1>
           <form class="search">
               <input class="form-control m-auto" type="text" name="search" placeholder="search todos" />
           </form>
       </header>
       <ul class="list-group todos mx-auto text-light">
           <li class="list-group-item d-flex justify-content-between align-items-center">
               <span>Play Guiter</span>
               <i class="far fa-trash-alt delete"></i>
           </li>
           <li class="list-group-item d-flex justify-content-between align-items-center">
               <span>Clean the floors</span>
               <i class="far fa-trash-alt delete"></i>
           </li>
           <li class="list-group-item d-flex justify-content-between align-items-center">
               <span>Clean Kitchen </span>
               <i class="far fa-trash-alt delete"></i>
           </li>
           <li class="list-group-item d-flex justify-content-between align-items-center">
               <span>Watch TV</span>
               <i class="far fa-trash-alt delete"></i>
           </li>
           <li class="list-group-item d-flex justify-content-between align-items-center">
               <span>BUY MILK</span>
               <i class="far fa-trash-alt delete"></i>
           </li>
           <li class="list-group-item d-flex justify-content-between align-items-center">
               <span>Pay House Rent</span>
               <i class="far fa-trash-alt delete"></i>
           </li>
       </ul>
       <form class="add text-center my-4">
           <div class="alert message"></div>
           <label class="text-light">Add a new todo...</label>
           <input class="form-control m-auto" type="text" name="add" />
           <input type="submit" value="Submit" class="mt-3 btn btn-secondary" />
       </form>
   </div>
   <script src="app.js"></script>
</body>
</html>