gpt4 book ai didi

Javascript ToDo 列表添加元素

转载 作者:行者123 更新时间:2023-11-28 05:34:41 24 4
gpt4 key购买 nike

我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com