Javascript ToDo 列表添加元素

标签 javascript html css debugging

我的 JS 代码有问题的编码新手。它在过去几天一直在工作,然后我不确定现在发生了什么,它在第 (17) 行 todos.push(task) 上给我一个错误;错误说“todos.push() 不是一个函数。”任何帮助将不胜感激。

 function get_todos()
 {
 var todos = new Array;
 var todos_str = localStorage.getItem('todo');
 if (todos_str !== null) {
    todos = JSON.parse(todos_str);
 }
 return todos;
 }


function add()
{
var task = document.getElementById('task').value;

var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));

show();

return false;
}


function remove()
{
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));

show();

return false;
}

function show()
{
var todos = get_todos();

var html = '<table>';
for(var i=0; i<todos.length; i++)
{
html += '<br><tr><strong>'+
'<input type="image" src="/Pictures/remove.png" class="remove"    id="' + i  +
'"></input>' + todos[i] + '</strong><input type="checkbox" name="cBox"   store="checkbox1"  id="isDone"><label for="cBox"</label></tr><br>';
};
html += '</table>';


document.getElementById('todos').innerHTML = html;

var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++)
{
    buttons[i].addEventListener('click', remove);
};
}

document.getElementById('add').addEventListener('click', add);
show();

我的 HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,   user-scalable=yes">
    </head>
    <body>
    <img id="mainImg"  src="\Pictures\mytodolist.jpg"
    <form>
    <div>
    <img  id="taskImg" src="\Pictures\tasks.jpg"
    <br>
    <br>
    <input  id="add" type="image" width='150' heigth='80'   src="\Pictures\addButton.png" ></input>
    <br>
    <input id="task">
    </div>
    <div id="todos"></div>

    <script src= "ToDo.js"></script>
    <link rel= "stylesheet" type= "text/css" href="todoStyle.css"/>
     </body>
    </html>

最佳答案

似乎在这里工作正常:http://codepen.io/ilanus/pen/xOXJXW你声明一个Array在你的get_todos()函数返回它,然后向其中添加元素 todos.push(task);

关于Javascript ToDo 列表添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296367/

相关文章:

javascript - 富文本编辑器显示不正确

javascript - Meteor:防止 findOne() 出现未定义的结果

html - CSS 子字符串匹配属性选择器 : Contains multiple class names

html - 文本不会右对齐

javascript - Javascript 对象如何工作?

javascript - yup.validate 仅返回错误数组中的单个字段

html - 为什么两个div不是并排的

javascript - jQuery Datepicker 未从此 min 属性获取 minDate

html - CSS 样式无法按我的需要工作

html - 如何在 IE 中 css html 显示图像,可以在 firefox、chrome 和 safari 中查看?