附录Click只会添加Div一次
我正在做一个时间表,要做列表网站。因此,我基本上为每个时间表块添加了DIV。我已经在yt上使用了本教程( https://youtu.be/mkesyvb4ouw )用于timetable块。 (在24:03)因此,在html中,有一个形式的输入,他为其使用常数“形式”并使用addeventListener提交。我已经使用了这个,我所有的时间表块都可以正常工作。我可以添加多个块,一切都很好。
之后,我做了一个要做 /目标部分,我决定将“形式”纳入自己的手中。所以我做到了:
// I tried const and var and the same thing happened
const todoAdd = document.querySelector("#new-todo"); // This is the button
const weekDiv = document.querySelector("#week-divs");
const todoDiv = document.createElement('div');
todoDiv.classList.add("todo-div");
这是我在时间块上所做的,它奏效了,然后我补充说:
todoAdd.onclick = function(){
weekDiv.appendChild(todoDiv);
}
当我这样做时,div是添加一次,仅此而已。如果我继续单击DIV,则会一次又一次地更换。
I'm doing a timetable and to do list website. So, I basically add divs for each timetable block. I've used this tutorial on yt (https://youtu.be/MkESyVB4oUw) for the timetable blocks. (At 24:03) So in HTML there's inputs in a form and he uses the constant "form" for it and uses an addEventListener submit. I've used this and all my timetable blocks work fine. I can add multiple blocks and everything works well.
After that I made a to do / goals section and I decided to take the "form" into my own hands. So I did:
// I tried const and var and the same thing happened
const todoAdd = document.querySelector("#new-todo"); // This is the button
const weekDiv = document.querySelector("#week-divs");
const todoDiv = document.createElement('div');
todoDiv.classList.add("todo-div");
This is what I did for the time blocks and it worked, and then I added:
todoAdd.onclick = function(){
weekDiv.appendChild(todoDiv);
}
When I do it like this, the div is added once and that's it. If I keep clicking the div just gets replaced again and again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在中间编写了这一点。因为当AddEventListener启动该表单时,那是我完成所有附加的时间。因此,简单的解决方案就是简单地在功能中添加创建元素。
如果我对它实际上只有一次不起作用,我可能会更早意识到这一点。我以为缺少一些简单的错误。我猜它只会附加一次,因为它仅读取一次,而在OnClick函数或AddeventListener中,它总是循环并重新阅读它吗?那是我的想法。希望这对某人有帮助。
I figured this out mid-writing it. Because when the addEventListener starts for the form, that's when I did all the appending. So the simple solution to this was simply adding the createElement inside the function.
I probably could've realised this sooner if I wasn't so confused about it actually working just once. I thought there was something missing instead of a simple mistake. I'm guessing it only appends once because it is only read once, while in an onclick function or addEventListener it always loops and re-reads it right? That's my thoughts. Hope this helps someone maybe.