Я хочу, чтобы название моей заметки, на которую я нажал, изменило НЕ первую заметку в списке. - PullRequest
0 голосов
/ 29 ноября 2018

Я пытаюсь завершить создание функциональности редактирования моего минимального приложения для создания заметок, но проблема в том, что после того, как я отредактирую свой заголовок и нажму кнопку «Сохранить», заголовок первой заметки в списке изменитсяно я хочу изменить название заметки, на которую я нажал.

Вот мой код JS:

// display list of notes on the side
    
      const noteContainer = document.querySelector(".column is-one-quarter")
      const noteList = document.querySelector(".menu-list")
    
      fetch('http://localhost:3000/api/v1/notes')
      .then(function(response) {
        return response.json();
      })
      .then(function(note) {
        note.forEach(function(note) {
          noteList.innerHTML += `<li><a id="note" data-id=${note.id} class="menu-item">${note.title}</a></li>`
        })
      })
    
      // display details of each note

      const noteDetail = document.querySelector(".note-detail")
    
      noteList.addEventListener('click', function(event) {
        if (event.target.className === "menu-item") {
          fetch(`http://localhost:3000/api/v1/notes/${event.target.dataset.id}`)
          .then(function(response) {
            return response.json()
          })
          .then(function(note) {
              noteDetail.innerHTML = `<h1 contenteditable="true" id="title" data-id=${note.id} class="subtitle is-2">${note.title}</h1><p contenteditable="true" id="body" data-id=${note.id} class="subtitle is-6">${note.body}</p><a id="save" class="button is-small">Save</a>`
    
    
         // i should be able to edit the title and body of a note when i click
         // on it and it should save when i click on the button.
    
         const noteId = event.target.dataset.id
         const editTitleInput = document.querySelector(`h1[data-id="${noteId}"]`)
         const editBodyInput = document.querySelector(`p[data-id="${noteId}"]`)
         const singleNote = document.querySelector("#note")
         const allNotes = document.querySelectorAll("li")
    
         noteDetail.addEventListener('click', function(event) {
           if (event.target.id === "save") {
             fetch(`http://localhost:3000/api/v1/notes/${noteId}`, {
               method: "PATCH",
               headers: {
                 'Content-Type': 'application/json',
                 'Accepts': 'application/json'
               },
               body: JSON.stringify({
                 title: editTitleInput.innerText,
                 body: editBodyInput.innerText
               })
             }).then(function(response) {
               return response.json()
             }).then(function(note) {
                    singleNote.innerText = editTitleInput.innerText
                })
              }
            })
          })
        }
      })

Вот мой HTML-код:

<div class="columns">

  <div class="column is-one-quarter">
    <p class="menu-label" style="font-size:15px;">
      Notes <i id="create" class="fas fa-plus-circle has-text-grey-light hvr-grow" style="margin-left: 10px; width: 20px; height: 30px; font-size: 24px;"></i>
    </p>
      <ul class="menu-list">

      </ul>
 </div>

  <div class="column is-three-fifths">
    <div class="note-detail">

    </div>
  </div>

  <div class="column">

  </div>

</div>

1 Ответ

0 голосов
/ 30 ноября 2018

Я вижу две проблемы.

Когда вы генерируете HTML для заметок здесь:

notes.forEach(function(note) {
   noteList.innerHTML += `<li><a id="note" data-id=${note.id} class="menu-item">${note.title}</a></li>`
})

Вы присваиваете каждой заметке один и тот же идентификатор (id="note")и затем позже, пытаясь установить innerText элемента с id="note", но он всегда получит первую заметку с идентификатором заметки.Ваш код выглядит следующим образом:

const singleNote = document.querySelector('#note');
singleNote.innerText = editTitleInput.innerText;

Поэтому, чтобы решить эту проблему, я предлагаю вам объединить идентификатор заметки с идентификатором элемента при генерации HTML (чтобы каждый из них имел уникальный идентификатор) следующим образом:

notes.forEach(function(note) {
     noteList.innerHTML += `<li><a id="note${note.id}" data-id=${note.id} class="menu-item">${note.title}</a></li>`
})

И затем получите соответствующий элемент со следующим запросом.

let singleNote = document.querySelector(`#note${noteId}`);

Вторая часть проблемы, которую я вижу, заключается в том, что вы добавляете eventListener в noteDetail, внутри кода слушателя события clickсписка заметок следующим образом:

noteList.addEventListener('click', function(event) {
...
  noteDetail.addEventListener('click', function(event) {
    ....
  })
})

Это означает, что при каждом нажатии на NoteList вы добавляете прослушиватель событий в noteDetail (что вы уже сделали).Поэтому при нажатии на noteDetail код будет выполняться несколько раз вместо одного.

Поэтому, чтобы решить эту проблему, я предлагаю вам поместить прослушиватель события click noteDetail вне прослушивателя события click noteList.

Вотмой полный код JS.Я прокомментировал части, которые я изменил.Надеюсь, это поможет:)

  const noteContainer = document.querySelector(".column is-one-quarter")
  const noteList = document.querySelector(".menu-list")

  fetch('http://localhost:3000/api/v1/notes')
  .then(function(response) {
    return response.json();
  })
  .then(function(notes) {
    //I changed the variable to "notes" instead of "note" as we're getting all notes here.
    notes.forEach(function(note) {
      //give a unique id to each note.
      noteList.innerHTML += `<li><a id="note${note.id}" data-id=${note.id} class="menu-item">${note.title}</a></li>`

    })
  })

  // display details of each note
  const noteDetail = document.querySelector(".note-detail");

  noteList.addEventListener('click', function(event) {
    if (event.target.className === "menu-item") {
      fetch(`http://localhost:3000/api/v1/notes/${event.target.dataset.id}`)
      .then(function(response) {
        return response.json()
      })
      .then(function(note) {
        noteDetail.innerHTML = `<h1 contenteditable="true" id="title" data-id=${note.id} class="subtitle is-2">${note.title}</h1><p contenteditable="true" id="body" data-id=${note.id} class="subtitle is-6">${note.body}</p><a id="save" class="button is-small">Save</a>`
      //I removed the noteDetail event listener from here
      })

    }
  })

  //Add the noteDetail event listener here (i.e outside of the noteList addEventListener code).
  noteDetail.addEventListener('click', function(event){ 

    if (event.target.id === "save") {
      //Now get the noteId of the current note being edited. 
      //We know this exists in both the data-id of the title and the body of noteDetail HTML 
      //so we retrieve it from one of these.
      //We could have also added a data-id to the save button of the noteDetail html. 
      //and then retrieved the noteId here with event.target.dataset.id
      let noteId = document.querySelector('#title').dataset.id;
      let editTitleInput = document.querySelector(`h1[data-id="${noteId}"]`);
      let editBodyInput = document.querySelector(`p[data-id="${noteId}"]`);
      //get the singleNote by it's unique id.
      let singleNote = document.querySelector(`#note${noteId}`);

      fetch(`http://localhost:3000/api/v1/notes/${noteId}`, {
        method: "PATCH",
        headers: {
          'Content-Type': 'application/json',
          'Accepts': 'application/json'
          },
          body: JSON.stringify({
            title: editTitleInput.innerText,
            body: editBodyInput.innerText
          })
      }).then(function(response) {
          return response.json()
      }).then(function(note) { 
          singleNote.innerText = editTitleInput.innerText;
      })
    }

  })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...