javascript - javascript 中的待办事项列表仅 : create, 删除、更新?

标签 javascript crud

我仅使用 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/

相关文章:

javascript - QT 使用 addToJavaScriptWindowObject()

c# - Reactive Extensions ... CRUD 应用中的示例

javascript - TypeError : this. props.onDelete 不是函数

mysql - 在 Mysql 上保存 2 月 30 日(日期格式)

javascript - 如何一起使用 getElementById 和 getElementsByTagName 获取元素的值

javascript - 如何选择下拉列表项

javascript - 如何在网站上使用谷歌翻译而不使用组合框更改语言?

javascript - 为什么我的代码没有获取 JSON 值?

javascript - 我可以使用 val() 插入或编辑文件输入吗?

php - 向数据库添加参数后,通过Postman POST数据时出现错误