Как динамически обновлять DOM элементами из массива (To Do list)
Уважаемые коллеги!
Помогите, плиз, с решением задачи. Есть простое приложение "список дел". Мне необходимо сделать так, чтобы при добавлении нового элемента в список, DOM каждый раз перерисовывался и на страницу выводился текущий список задач из массива, а не хранился бы в HTML, а также чтобы удалять элементы. Гуглил, но везде в основном реализация через HTML, т.е. удаление просто симулируется за счет стилей: display: none HTML: <!DOCTYPE html> <html> <head> <title>JS - ToDoList</title> <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> --> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="listName"> <hr> <h1 id="shopListName">Shopping List</h1> <p id="getItDone">Get it done today</p> <hr> </div> <div id="listBody"> <!-- It is better to put <INPUT> and BUTTON within a <FORM>--> <form onsubmit="createListElement(event)"> <input id="userinput" type="text" placeholder="enter items"> <!-- It is possible to add ONCLICK to a <BUTTON> and the event is transferred in the Argument--> <!-- Button type submit. Works within <FORM> only. And then the whole <FORM> shall be submitted (ONSUBMIT)--> <button id="enter" type="submit">Add item</button> </form> <ul> </ul> </div> <script type="text/javascript" src="script.js"></script> </body> </html> Вот js код:
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var array = [];
function inputLength() {
return input.value.length;
}
function createListElement(event) {
event.preventDefault();
let inputValue = event.target[0].value;
if (!inputValue) {
console.log("empty field");
return;
};
let obj = {
value: inputValue,
isDone: false,
id: array.length
}
array.push(obj);
console.log(event);
console.log(array);
renderDom();
}
function renderDom() {
for (i=0; i<array.length; i++) {
var btnDel = document.createElement("button");
var li = document.createElement("li");
ul.appendChild(li);
li.appendChild(document.createTextNode(input.value));
btnDel.appendChild(document.createTextNode("X"));
li.appendChild(btnDel);
btnDel.addEventListener("click", deleteElement);
var setAttr = array[i].id;
btnDel.setAttribute("id", setAttr);
};
input.value = "";
};
function deleteElement(event) {
// create a delete button
let btnId = event.target.id;
if (btnId == )
console.log(btnId);
}
Заранее благодарен за помощь! |
<ul class="todos"></ul>
<input type="text" class="todotext">
<button class="addtodo">add todo</button>
<script>
let todos = []
const todosEl = document.querySelector('.todos')
const todoTextEl = document.querySelector('.todotext')
const update = () => {
todosEl.innerHTML = todos.map(todo => `<li>${todo.id} - ${todo.text} <button data-todo-id=${todo.id}>x</button></li>`).join('')
}
document.querySelector('.addtodo').addEventListener('click', () => {
todos.push({
id: todos.length > 0 ? todos.reduce((p, c) => p.id > c.id ? p : c).id + 1 : 1,
text: todoTextEl.value,
})
todoTextEl.value = ''
update()
})
todosEl.addEventListener('click', e => {
todos = todos.filter(todo => todo.id !== parseInt(e.target.dataset.todoId))
update()
})
</script>
5 минут ) |
:)
если id не нужен
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
</head>
<body>
<ul class="todos"></ul>
<input type="text" class="todotext">
<button class="addtodo">add todo</button>
<script>
let todos = [];
const todosEl = document.querySelector('.todos');
const todoTextEl = document.querySelector('.todotext');
const update = () => {
todosEl.innerHTML = todos.map((todo,i)=> `<li>${i + 1} - ${todo.text} <button data-todo-id=${i}>x</button></li>`).join('')
}
document.querySelector('.addtodo').addEventListener('click', () => {
todos.push({
text: todoTextEl.value
})
todoTextEl.value = ''
update()
})
todosEl.addEventListener('click', ({target}) => {
target = target.closest('[data-todo-id]');
if(target){
todos.splice(target.dataset.todoId, 1);
update()
}
})
</script>
</body>
</html>
|
:)
если id нужен
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
</head>
<body>
<ul class="todos"></ul>
<input type="text" class="todotext">
<button class="addtodo">add todo</button>
<script>
let todos = [], id = 0;
const todosEl = document.querySelector('.todos');
const todoTextEl = document.querySelector('.todotext');
const update = () => {
todosEl.innerHTML = todos.map((todo,i)=> `<li>${todo.id} - ${todo.text} <button data-todo-id=${i}>x</button></li>`).join('')
}
document.querySelector('.addtodo').addEventListener('click', () => {
todos.push({
text: todoTextEl.value,
id : id++
})
todoTextEl.value = ''
update()
})
todosEl.addEventListener('click', ({target}) => {
target = target.closest('[data-todo-id]');
if(target){
todos.splice(target.dataset.todoId, 1);
update()
}
})
</script>
</body>
</html>
|
| Часовой пояс GMT +3, время: 06:10. |