我仅使用 JavaScript 创建待办事项列表。 Html 如下:
<section>
<input id="user_input" name="user_input" type="text" />
<button value="Add" id="add" onclick="addNotes()">Add</button>
<ul id="note_List"></ul>
</section>
JavaScript 就是这样,但我做错了。所以请纠正我,我是 JS 新手。
<script>
function addNotes() {
var input = document.getElementById('user_input').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('note_List');
noteList.innerHTML += "<li>" + input + "<button id='delete'>clear</button> <span id='edit'>Edit</span></li>";
}
}
document.getElementById('delete').onclick = function () {
var list = document.getElementById('delete');
}
</script>
最佳答案
您的代码只有两个错误。 首先,在为“delete”定义 onclick evento 之前,您还没有关闭第一个函数(“addNotes()”)。
其次,您的代码将生成许多具有相同“id”的元素,这可能会出现问题。 “Id”应该是唯一的。尝试将“删除”定义为一个类。
然后,使用“getElementsByClassName”而不是“getElementById”。
这很棘手。或者,您可以直接向生成的按钮提供“onclick”事件,而不是使用任何“删除”类。为了访问和删除(例如)按钮“clear”所在的“li”,您必须通过相当复杂的调用来访问其父级:
this.parentNode.parentNode.removeChild(this.parentNode)
<script>
function addNotes() {
var input = document.getElementById('user_input').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('note_List');
noteList.innerHTML += "<li>" + input + "<button onclick='this.parentNode.parentNode.removeChild(this.parentNode)'>clear</button> <span class='edit'>Edit</span></li>";
}
}
</script>
关于javascript - javascript 中的待办事项列表仅 : create, 删除、更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34374737/