简体   繁体   English

如何多次使用 append HTML 元素

[英]How to append HTML element multiple times

i do an event to add input value to a list when i click the button or press enter key, it's work but when i click again on button or enter key nothing happening.当我单击按钮或按回车键时,我会执行一个事件以将输入值添加到列表中,它可以工作,但是当我再次单击按钮或输入键时没有任何反应。 js code: js代码:

// important vars 
const btn = document.getElementById('btn');
const inputV = document.getElementById('input').value;
const input = document.getElementById('input');
const todoUl = document.createElement("ul");
const todoLi = document.createElement("li")
const todoList = document.getElementById('todolist'); // this the div that contain ul and li
const form = document.getElementById('from');

// this function is for add input value and create list's 
function addTodo(todo) {
    form.appendChild(todoUl);
    todoUl.appendChild(todoLi);
    todoLi.innerText = inputV    
};

// later ..
form.addEventListener('submit' , (e) => {
    e.preventDefault(); 

    addTodo()

});
// This code is for clean input value 

appendChild method appends a Node to the elements childlist, but also removes it from the original place . appendChild方法将一个 Node 附加到元素子列表中,但也将其从原始位置中删除 By the first call, it is not in the DOM yet, so it appends.通过第一次调用,它还没有在 DOM 中,所以它附加了。 In the later call, it is removed and re-added to the DOM, so effectively nothing happens.在后面的调用中,它被移除并重新添加到 DOM 中,因此实际上什么也没发生。

If you want to append it multiple times, you need toclone it.如果你想多次 append 它,你需要克隆它。 In your case:在你的情况下:

todoUl.appendChild(todoLi.clone(1)); // 1 = deep

If you just want to append li item, you probably don't want to clone/add the todoUl element in the subsequent calls.如果您只想 append li项目,您可能不想在后续调用中克隆/添加todoUl元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM