【问题标题】:How to append HTML element multiple times如何多次附加 HTML 元素
【发布时间】:2020-11-26 17:51:29
【问题描述】:

当我单击按钮或按 Enter 键时,我会执行一个事件以将输入值添加到列表中,它可以工作,但是当我再次单击按钮或 Enter 键时没有任何反应。 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 

【问题讨论】:

  • 你能分享你的HTML代码和你所有的流程吗?成功了,还有一个问题。

标签: javascript html object dom


【解决方案1】:

appendChild 方法将一个节点附加到元素子列表中,但也会将其从原始位置移除。通过第一次调用,它还没有在 DOM 中,所以它附加了。在后面的调用中,它被移除并重新添加到 DOM 中,所以实际上什么也没发生。

如果你想多次追加它,你需要clone它。在你的情况下:

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

如果您只想追加li 项目,您可能不想在后续调用中克隆/添加todoUl 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    相关资源
    最近更新 更多