[英]Why does my onclick property not run the function upon submit?
everyone.每个人。 Bit of a JS noob.
有点 JS 菜鸟。 First question on here.
第一个问题在这里。 I tried being more specific through the Stack Overflow submission guidelines but I'm not sure how to, as I'm not sure what's wrong with this.
我尝试通过 Stack Overflow 提交指南更加具体,但我不确定如何,因为我不确定这有什么问题。 Tips to become a better asker are appreciated.
成为更好的提问者的提示值得赞赏。
I'm building a simple JS todo list, trying not to use video tutorials.我正在构建一个简单的 JS 待办事项列表,尽量不使用视频教程。 I just simply can't figure out what's wrong with this.
我只是无法弄清楚这有什么问题。 On hitting the 'submit' button, nothing happens either in the console log or on the actual page.
在点击“提交”按钮时,控制台日志或实际页面中都没有发生任何事情。 What am I doing wrong?
我究竟做错了什么?
let todoInput = document.getElementById("input"); let list = document.getElementById("submit"); let form = document.getElementById("form"); list.onclick = function addTodo(e) { e.preventDefault(); // todo div const todoDiv = document.createElement('div'); todoDiv.classList.add('todo'); // todo LI const newTodo = document.createElement('li'); newTodo.innerText = todoInput.value; newTodo.classList.add('todo-item'); todoDiv.appendChild(newTodo); if (todoInput.value === "") { return null } };
<h1>TODO LIST</h1> <form id="form" onload="false"> <input id="input" type="text"> <input id="submit" type="submit" value="Submit"> </form> <div id="output"></div>
That's because when you've created the todoDiv
element, you are not appending it to your DOM at all.那是因为当您创建了
todoDiv
元素时,您根本没有将它附加到您的 DOM 中。 If you want to append it to the #output
element, you can add the following line at the very end:如果要将 append 它添加到
#output
元素,可以在最后添加以下行:
document.getElementById('output').appendChild(todoDiv);
NOTE: Your li
elements must be appended to <ul>
elements.注意:您的
li
元素必须附加到<ul>
元素。 You can just change #output
to be a <ul>
element and append your list items directly to it:您可以将
#output
更改为<ul>
元素,并将 append 您的列表项直接更改为它:
See proof-of-concept below:请参阅下面的概念验证:
let todoInput = document.getElementById("input"); let list = document.getElementById("submit"); let form = document.getElementById("form"); let output = document.getElementById("output"); list.onclick = function addTodo(e) { e.preventDefault(); // todo LI const newTodo = document.createElement('li'); newTodo.innerText = todoInput.value; newTodo.classList.add('todo-item'); output.appendChild(newTodo); };
<h1>TODO LIST</h1> <form id="form" onload="false"> <input id="input" type="text"> <input id="submit" type="submit" value="Submit"> </form> <ul id="output" class="todo"></ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.