2 回答

TA貢獻1829條經驗 獲得超7個贊
當您嘗試按 ID 刪除時,它會獲取找到的第一個 ID。
要刪除正確的內容,請發送點擊。this
<button onclick="removeContent(this)">Remove this</button>
并在您的函數中處理它:
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>

TA貢獻1942條經驗 獲得超3個贊
在移除按鈕中,執行以下操作:
<!-- The "this" keyword is a reference to the button element itself --> <button onclick="removeContent(this)">Remove this</button>
在你的腳本中:
function removeContent(element) { element.parentNode.remove(); }
添加回答
舉報