簡體   English   中英

如何使用 JavaScript 中的一個 function 從多個 div 中刪除特定的 div?

[英]How do I remove a specific div out of many using one function in JavaScript?

我正在學習 JavaScript,這對我來說是一個練習場景。

我已經有了一個克隆內容的按鈕,在已克隆的內容中,有一個按鈕可以將其刪除。

當我點擊提示您刪除內容的按鈕時,它刪除了第一組內容。

我想要發生的是,當您單擊提示您刪除內容的按鈕時,它會刪除與該按鈕相關的內容,而不會刪除其他任何內容。

這是 CodePen 鏈接。

https://codepen.io/JosephChunta/pen/YzwwgvQ

這是代碼。

 function addContent() { var itm = document.getElementById("newContent"); var cln = itm.cloneNode(true); document.getElementById("placeToStoreContent").appendChild(cln); } function removeContent() { var x = document.getElementById("content").parentNode.remove(); } // This is for debug purposes to see which content is which document.getElementById('orderContent').addEventListener('click', function(e) { const orderedNumber = document.querySelectorAll('.thisIsContent'); let i = 1; for (p of orderedNumber) { p.innerText = '' + (i++); } });
 .contentThatShouldBeHidden { display: none; }
 <div id="placeToStoreContent"> </div> <button id="orderContent" onclick="addContent()">Add Content</button> <div class="contentThatShouldBeHidden"> <div id="newContent"> <div id="content"> <p class="thisIsContent">This is a prompt</p> <button onclick="removeContent()">Remove this</button> <hr /> </div> </div> </div>

當您嘗試按 ID 刪除時,它會使用它找到的第一個 ID。

要刪除正確的內容,請發送this onclick。

  <button onclick="removeContent(this)">Remove this</button>

並在你的 function 中處理:

function removeContent(el) {
  el.parentNode.remove();
}

例子:

 function addContent() { var itm = document.getElementById("newContent"); var cln = itm.cloneNode(true); document.getElementById("placeToStoreContent").appendChild(cln); } function removeContent(el) { el.parentNode.remove(); } // This is for debug purposes to see which content is which document.getElementById('orderContent').addEventListener('click', function(e) { const orderedNumber = document.querySelectorAll('.thisIsContent'); let i = 1; for (p of orderedNumber) { p.innerText = '' + (i++); } });
 .contentThatShouldBeHidden { display: none; }
 <div id="placeToStoreContent"> </div> <button id="orderContent" onclick="addContent()">Add Content</button> <div class="contentThatShouldBeHidden"> <div id="newContent"> <div id="content"> <p class="thisIsContent">This is a prompt</p> <button onclick="removeContent(this)">Remove this</button> <hr /> </div> </div> </div>

在您的刪除按鈕中,執行以下操作:

<!-- The "this" keyword is a reference to the button element itself -->
<button onclick="removeContent(this)">Remove this</button>

在您的 javascript 中:

function removeContent(element) {
  element.parentNode.remove();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM