Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 09.10.2019, 16:30
Новичок на форуме
Отправить личное сообщение для Mikepolo Посмотреть профиль Найти все сообщения от Mikepolo
 
Регистрация: 09.10.2019
Сообщений: 1

Как динамически обновлять 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);

}

Заранее благодарен за помощь!
Ответить с цитированием
  #2 (permalink)  
Старый 09.10.2019, 16:50
Аватар для SuperZen
Профессор
Отправить личное сообщение для SuperZen Посмотреть профиль Найти все сообщения от SuperZen
 
Регистрация: 08.11.2017
Сообщений: 642

<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 минут )
Ответить с цитированием
  #3 (permalink)  
Старый 09.10.2019, 17:15
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068


если 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>
Ответить с цитированием
  #4 (permalink)  
Старый 09.10.2019, 17:17
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068


если 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>
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как вы относитесь к наркоманам? Maxmaxmaximus7 Оффтопик 7 05.02.2014 13:29
Как заполнить форму на другом сайте динамически gaintbiz AJAX и COMET 1 03.01.2014 16:53
Как динамически создавать поля и записать значения с массива ? Sergios90 Общие вопросы Javascript 7 19.11.2013 18:34
Замена элементов массива элементами массива prostoix Javascript под браузер 4 24.10.2013 17:36
наследование установок динамически создаваемыми элементами majestic jQuery 1 15.09.2008 13:21