JavaScript:仅删除所选用户输入,而不删除整个HTML块。

huangapple go评论68阅读模式
英文:

JavaScript: Delete only the selected user input and not the entire HTML block

问题

以下是翻译好的部分:

我在尝试弄清楚如何删除特定用户输入而不是整个HTML块时遇到了问题。我知道删除按钮在HTML ID 'noteDelete'上触发,该ID是每个用户输入的父级,但是我不确定如何为每个用户输入设置特定的ID。如果这是解决方案,那么是否需要为每个用户输入创建一个新的ID,以便删除按钮在每个输入上触发?以下是代码:

// 事件目标
let titleArea = document.getElementById('title')
let noteArea = document.getElementById('note')
let submitNoteButton = document.getElementById('addNote')
let noteSum = document.getElementById('noteValue')
let viewNoteButton = document.getElementById('viewNote')

// 事件处理程序
submitNoteButton.addEventListener('click', () => {
  let listTitle = title.value
  let noteInput = noteArea.value
  let listNote = document.createElement('div')
  let noteDelete = document.createElement('button')
  noteDelete.innerHTML = 'Delete'
  noteDelete.setAttribute('id', 'noteDelete')
  
  if (listTitle) {
    listNote.innerHTML =
      `<h3>${listTitle}</h3>
       <p>${noteInput}</p>
       <button type="button" id="deleteNote" form="delete">Delete</button>
       <button type="button" id="viewNote" form="view">View</button>`
  }
  
  noteSum.appendChild(listNote)
  noteSum.appendChild(noteDelete)
  noteArea.value = ""
  titleArea.value = ""

  let deleteNoteButton = document.getElementById('noteDelete')
  deleteNoteButton.addEventListener('click', () => {
    let deleteValue = document.querySelector('noteDelete')
    deleteValue.remove()
  })
})
<body>
  <section class="inputField">
    <h1>Note Taker</h1>
    <h3>Add A New Note:</h3>
    <form id="inputText">
      <div>
        <label for="title">Title:</label>
        <input type="text" name="title" id="title">
      </div>
      <div>
        <label for="note">Note:</label>
        <textarea id="note" name="note" rows="2" cols="100"></textarea>
      </div>
    </form>
    <button type="button" id="addNote" form="note">Add Note</button>
  </section>
  <section class="outputField">
    <form id="outputValue">
      <div id="noteValue">
        <!-- <h3>标题</h3>
             <p>我想买个汉堡!</p>
             <button type="button" id="deleteNote" form="delete">删除</button>
             <button type="button" id="viewNote" form="view">查看</button> -->
      </div>
    </form>
  </section>
</body>
英文:

I am having problems trying to figure out how to delete one specific user input instead of the entire HTML block. I am aware that the delete button fires on the HTML ID 'noteDelete' which is the parent of each user input, however I'm not sure how to set a specific ID for each user input. If that is the solution. For each user input would a new ID have to be created in order for the delete button to fire on each input? Here's the code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

//Event Targets
let titleArea = document.getElementById(&#39;title&#39;)
let noteArea = document.getElementById(&#39;note&#39;)
let submitNoteButton = document.getElementById(&#39;addNote&#39;)
let noteSum = document.getElementById(&#39;noteValue&#39;)
//let noteDeleteButton = document.querySelectorAll(&#39;noteDelete&#39;)
//let deleteNoteButton = document.getElementById(&#39;noteDelete&#39;)
let viewNoteButton = document.getElementById(&#39;viewNote&#39;)



//Event Handlers
submitNoteButton.addEventListener(&#39;click&#39;, () =&gt; {
  let listTitle = title.value
  let noteInput = noteArea.value
  let listNote = document.createElement(&#39;div&#39;)
  let noteDelete = document.createElement(&#39;button&#39;)
  noteDelete.innerHTML = &#39;Delete&#39;
  noteDelete.setAttribute(&#39;id&#39;, &#39;noteDelete&#39;)
  //listNote.classList.add(&#39;listNote&#39;)
  if (listTitle) {
    listNote.innerHTML =
      `&lt;h3&gt;${listTitle}&lt;/h3&gt;
        &lt;p&gt;${noteInput}&lt;/p&gt;
        &lt;button type=&quot;button&quot; id=&quot;deleteNote&quot; form=&quot;delete&quot;&gt;Delete&lt;/button&gt;
        &lt;button type=&quot;button&quot; id=&quot;viewNote&quot; form=&quot;view&quot;&gt;View&lt;/button&gt;`
  }
  noteSum.appendChild(listNote)
  noteSum.appendChild(noteDelete)
  noteArea.value = &quot;&quot;
  titleArea.value = &quot;&quot;

  let deleteNoteButton = document.getElementById(&#39;noteDelete&#39;)
  deleteNoteButton.addEventListener(&#39;click&#39;, () =&gt; {
    let deleteValue = document.querySelector(&#39;noteDelete&#39;)
    deleteValue.remove()
  })

})

<!-- language: lang-html -->

&lt;body&gt;
  &lt;section class=&quot;inputField&quot;&gt;
    &lt;h1&gt;Note Taker&lt;/h1&gt;
    &lt;h3&gt;Add A New Note:&lt;/h3&gt;
    &lt;form id=&quot;inputText&quot;&gt;
      &lt;div&gt;
        &lt;label for=&quot;title&quot;&gt;Title:&lt;/label&gt;
        &lt;input type=&quot;text&quot; name=&quot;title&quot; id=&quot;title&quot;&gt;
      &lt;/div&gt;

      &lt;div&gt;
        &lt;label for=&quot;note&quot;&gt;Note:&lt;/label&gt;
        &lt;textarea id=&quot;note&quot; name=&quot;note&quot; rows=&quot;2&quot; cols=&quot;100&quot;&gt;&lt;/textarea&gt;
      &lt;/div&gt;
    &lt;/form&gt;
    &lt;button type=&quot;button&quot; id=&quot;addNote&quot; form=&quot;note&quot;&gt;Add Note&lt;/button&gt;
  &lt;/section&gt;
  &lt;section class=&quot;outputField&quot;&gt;
    &lt;form id=&quot;outputValue&quot;&gt;
      &lt;div id=&quot;noteValue&quot;&gt;
        &lt;!--&lt;h3&gt;Title&lt;/h3&gt;
                &lt;p&gt;I would like to buy a AMMMBURGER!&lt;/p&gt;
                &lt;button type=&quot;button&quot; id=&quot;deleteNote&quot; form=&quot;delete&quot;&gt;Delete&lt;/button&gt;
                &lt;button type=&quot;button&quot; id=&quot;viewNote&quot; form=&quot;view&quot;&gt;View&lt;/button&gt;--&gt;
      &lt;/div&gt;
    &lt;/form&gt;
  &lt;/section&gt;

<!-- end snippet -->

答案1

得分: 1

以下是翻译好的部分:

问题出在你将会有多个笔记,每个笔记都有自己的删除按钮。首先,不要在按钮上使用 Id,因为每次添加一个笔记时,两个或更多的按钮将具有相同的 Id。相反,你可以在删除按钮上使用一个类,例如,<button class="delete-note-btn">删除笔记</button> 然后你可以使用 事件代理 来定位存在于 HTML 文件中的父元素(或其他元素)。类似这样的代码:

const notesList = document.querySelector(".note-list") // 存储你的笔记的容器元素。

notesList.addEventListener("click", (e) => {
    if (e.target.classList.contains('delete-note-btn')) { // 被点击的元素是删除笔记按钮
        // 删除特定的笔记
        // 假设笔记是删除按钮的父元素,那么我们可以这样选择它
        let note = e.target.parentElement
        // 移除(删除)笔记
        note.remove()  
    }
})

希望有所帮助。

英文:

So the problem you are having is that you will be having multiple notes, each having its own delete button. First, don't use an Id on the button because every time a note is added, two or more buttons will have the same Id. Instead, you can use a class on the delete button, for example, &lt;button class=&quot;delete-note-btn&gt;delete note&lt;/button&gt; Then you can use event delegation to target a parent element (or so) that exists in the HTML file. something like this.

const notesList = document.querySelector(&quot;.note-list&quot;) // The container element where your notes will be stored.

notesList.addEventListener(&quot;click&quot;, (e) =&gt; {
    if (e.target.classList.contains(&#39;delete-note-btn&#39;) { // the element clicked is the delete note button
    // Delete the specific note
    // assuming the note is the delete button&#39;s parent element then we can select it like this
    let note = e.target.parentElement
    // remove (delete) the note
    note.remove()  
}
})

Hope it helps.

答案2

得分: 0

你完全不需要使用ID。你可以从触发EventListenerEvent参数中受益,以识别你正在修改的是哪个注释。具体来说,因为你实际上是要删除div,而这个div是用户点击的删除按钮的直接父元素,你可以使用e.currentTarget.parentNode.remove();来识别该元素。

这将确保只有你点击的那个注释被删除,而不会影响其他注释或担心找到正确的id

值得一提的是,两个元素永远不应该具有相同的id,所以在可能需要删除/查询多个元素的情况下,最好使用类(class),就像@ismail在他的回答中建议的那样。

工作示例:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->
    // 事件目标
    let titleArea = document.getElementById('title');
    let noteArea = document.getElementById('note');
    let submitNoteButton = document.getElementById('addNote');
    let noteSum = document.getElementById('noteValue');
    let viewNoteButton = document.getElementById('viewNote');

    // 事件处理程序
    submitNoteButton.addEventListener('click', () => {
      let listTitle = title.value;
      let noteInput = noteArea.value;
      let listNote = document.createElement('div');

      let noteDelete = document.createElement('button');
      noteDelete.innerHTML = '删除';

      if (listTitle) {
        listNote.innerHTML =
          `<h3>${listTitle}</h3>
                <p>${noteInput}</p>
                <button type="button" form="view">查看</button>`
      }

      noteSum.appendChild(listNote);

      noteArea.value = "";
      titleArea.value = "";

      noteDelete.addEventListener('click', (e) => {
        e.target.parentNode.remove();
      });
      listNote.appendChild(noteDelete);
    })

<!-- language: lang-html -->
    <body>
      <section class="inputField">
        <h1>笔记记录器</h1>
        <h3>添加新笔记:</h3>
        <form id="inputText">
          <div>
            <label for="title">标题:</label>
            <input type="text" name="title" id="title">
          </div>

          <div>
            <label for="note">笔记:</label>
            <textarea id="note" name="note" rows="2" cols="100"></textarea>
          </div>
        </form>
        <button type="button" id="addNote" form="note">添加笔记</button>
      </section>
      <section class="outputField">
        <form id="outputValue">
          <div id="noteValue">
          </div>
        </form>
      </section>
    </body>

<!-- end snippet -->
英文:

You don't need to use IDs at all. You can benefit from the Event parameter of triggering an EventListener to identify which note you're modifying. Specifically, since you're essentially deleting the div that is the direct parent of the delete button the user is clicking, you can identify that element using e.currentTarget.parentNode.remove();.

This will guarantee that only the note you are clicking gets deleted without affecting the rest or worrying about finding the correct id.

It's also worth mentioning that no two elements should ever have the same id, so in situations where you might want to delete/query multiple elements, it's better to use a class like @ismail suggested in his answer.

working snippet:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

//Event Targets
let titleArea = document.getElementById(&#39;title&#39;);
let noteArea = document.getElementById(&#39;note&#39;);
let submitNoteButton = document.getElementById(&#39;addNote&#39;);
let noteSum = document.getElementById(&#39;noteValue&#39;);
let viewNoteButton = document.getElementById(&#39;viewNote&#39;);
//Event Handlers
submitNoteButton.addEventListener(&#39;click&#39;, () =&gt; {
let listTitle = title.value;
let noteInput = noteArea.value;
let listNote = document.createElement(&#39;div&#39;);
let noteDelete = document.createElement(&#39;button&#39;);
noteDelete.innerHTML = &#39;Delete&#39;;
if (listTitle) {
listNote.innerHTML =
`&lt;h3&gt;${listTitle}&lt;/h3&gt;
&lt;p&gt;${noteInput}&lt;/p&gt;
&lt;button type=&quot;button&quot; form=&quot;view&quot;&gt;View&lt;/button&gt;`
}
noteSum.appendChild(listNote);
noteArea.value = &quot;&quot;;
titleArea.value = &quot;&quot;;
noteDelete.addEventListener(&#39;click&#39;, (e) =&gt; {
e.target.parentNode.remove();
});
listNote.appendChild(noteDelete);
})

<!-- language: lang-html -->

&lt;body&gt;
&lt;section class=&quot;inputField&quot;&gt;
&lt;h1&gt;Note Taker&lt;/h1&gt;
&lt;h3&gt;Add A New Note:&lt;/h3&gt;
&lt;form id=&quot;inputText&quot;&gt;
&lt;div&gt;
&lt;label for=&quot;title&quot;&gt;Title:&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;title&quot; id=&quot;title&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;label for=&quot;note&quot;&gt;Note:&lt;/label&gt;
&lt;textarea id=&quot;note&quot; name=&quot;note&quot; rows=&quot;2&quot; cols=&quot;100&quot;&gt;&lt;/textarea&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;button type=&quot;button&quot; id=&quot;addNote&quot; form=&quot;note&quot;&gt;Add Note&lt;/button&gt;
&lt;/section&gt;
&lt;section class=&quot;outputField&quot;&gt;
&lt;form id=&quot;outputValue&quot;&gt;
&lt;div id=&quot;noteValue&quot;&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/section&gt;
&lt;/body&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月20日 21:03:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定