【发布时间】:2019-12-27 07:44:11
【问题描述】:
我正在使用 javaScript、HTML 和 CSS 制作一个待办事项列表,并且要插入任何元素,我们必须单击提交(添加)按钮,但我希望当我们从键盘按下输入按钮时,元素将插入或提交按钮会按,我不知道该怎么做,因为我是 javascript 新手
这是代码
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>
<input id="task"><button id="add">Add</button>
<hr>
<div id="todos"></div>
<script src="nv.js"></script>
</body>
</html>
Java 脚本
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 = '<ul>';
for(var i=0; i<todos.length; i++) {
html += '<li>' + todos[i] + '<button class="remove" id="' + i + '">x</button></li>';
};
html += '</ul>';
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();
谢谢
【问题讨论】:
标签: javascript html visual-studio javascript-objects