@700Hp

Как отобразить текст в шаблоне?

Есть TODO LIST.
Он создаёт TODO элементы.
Хочу сделать так, чтобы у создаваемого элемента, была возможность добавить ему описание(или назовём её подзадачу).
Сервер откликается, подзача создаётся. Как отобразить её?

Переменные:
const ensineInput = document.querySelector('#ensineInput')
const todos = document.querySelector('#todos')
let todoList = []
let todoItemElems = []


// Подгрузка списка задач

function resArray() {
  fetch('/todos/api/todo', {
    method: 'get',
  })
    .then((res) => res.json())
    .then((todos) => {
      todoList = todos
      fillHtmlList()
      counter(todoList)
    })
    .catch((e) => console.log(e))
}

resArray()

// Создание основного элемента

function addTodoItem() {
  const title = ensineInput.value

  if (!title) {
    return
  }

  fetch('/todos/api/todo', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title }),
  })
    .then((res) => res.json())
    .then(({ todo }) => {
      todoList.push(todo)
      fillHtmlList()
    })
    .catch((e) => console.log(e))
}

ensineInput.addEventListener('keypress', (e) => {
  if (e.key === 'Enter') {
    if (!ensineInput.value) {
      return
    }
    addTodoItem()
    ensineInput.value = ''
  }
})

function fillHtmlList() {
  todos.innerHTML = ''
  if (todoList.length != 0) {
    filterTodos()
    todoList.forEach((item, index) => {
      todos.innerHTML += createTemplate(item, index)
    })
    todoItemElems = document.querySelectorAll('.todo__item')
    counter(todoList)
  }
}

function createTemplate(item, index) {
  return `
    <li class="todo__item ${item.done ? 'todo__item--done' : ''}" id="${
    item._id
  }">
    <div class="todo__content">

    <div class="todo__left">
      <div class="todo__done ${item.done ? 'done' : ''}" onClick="doneTodo('${
    item._id
  }')">
        <img class='todo__img todo__img--done' src='img/${
          item.done ? 'check' : 'circle'
        }.svg' alt='' />
      </div>

      <div class="todo__info">
        ${item.title}
      </div>

      <div class="note__form">
        <input type="text" name="noteTitle" class="input input--note" placeholder="Введите примечание" id="${index}">
        <button type="button" class="btn btn--notes" onClick="addNotes('${
          item._id
        }',${index})">
          <img class="todo__img todo__img--create" src="img/magic-wand.svg">
        </button>
    </div>
    </div>

    ${
      item.notes.length
        ? `
        <ol class="notes">
         <li><b>Желаемое отображение элементов==============================================</b></li>
        </ol>`
        : ''
    }

    <div class="todo__right">
      <button type="button" class="btn btn--close" onClick="deleteTask('${
        item._id
      }', ${index})">
        <img class='todo__img todo__img--close' src='img/close.svg' alt='удалить' />
      </button>
    </div>
    </div>
    </li>
    `
}

function deleteTask(id, index) {
  fetch('/todos/api/todo/' + id, {
    method: 'delete',
  })
    .then(() => {
      removeItemTask(index)
    })
    .catch((e) => console.log(e))
}

function removeItemTask(index) {
  todoItemElems[index].classList.add('delete')
  setTimeout(() => {
    todoList.splice(index, 1)
    counter(todoList)
    fillHtmlList()
  }, 300)
}

function doneTodo(id) {
  fetch('todos/api/todo/' + id, {
    method: 'put',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ done: true }),
  })
    .then((res) => res.json())
    .then(({ todo }) => {
      const idx = todoList.findIndex((t) => t._id === todo._id)
      todoList[idx].done = todo.done
      fillHtmlList()
    })
    .catch((e) => console.log(e))
}

function filterTodos() {
  let activeTodos = []
  let completedTodos = []
  if (todoList.length) {
    todoList.forEach((item) => {
      if (item.done === false) {
        return activeTodos.push(item)
      } else {
        return completedTodos.push(item)
      }
    })
  }
  todoList = [...activeTodos, ...completedTodos]
}

function addNotes(id, index) {
  const input = document.getElementById(`${index}`).value

  if (!input) {
    return
  }

  fetch('/todos/api/todo/notes/' + id, {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ input }),
  })
    .then((res) => res.json())

    .catch((e) => console.log(e))
}


Структура элемента в БД
6135becd6d6fc195308820.png
  • Вопрос задан
  • 83 просмотра
Решения вопроса 1
Red_Devi1
@Red_Devi1
Находите нужный <li>по дата-атрибуту и добавляйте в его ol. notes всё что душе угодно.
Не совсем ясно на каком этапе сложности, мб неправильно понимаю вопрос.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы