3 回答

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
因?yàn)槟M诙鄠€(gè)按鈕上添加相同的邏輯,所以應(yīng)該使用 而不是 。該 ID 應(yīng)該是唯一的。使用?Element.closest(),您可以找到最接近單擊發(fā)生的父節(jié)點(diǎn),直到找到與提供的選擇器字符串匹配的節(jié)點(diǎn)。在此處閱讀代碼示例中的注釋classes
ids
?// deleteButtons is will be an array of buttons
const deleteButtons = document.querySelectorAll('.del');
deleteButtons.forEach( button => {
? // add the event listener to each button
? button.addEventListener('click', removeMe);?
});
function removeMe() {
? ?// this is the button
? ?// from the button you want to move up in DOM?
? ?// and find the closes <li> to remove
? ?this.closest('li').remove();?
}
<h1>The List</h1>
<ul>
? <li>Delete me<button class="del">x</button></li>
? <li>Delete me too<button class="del">x</button></li>
</ul>

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
正如其他人所說(shuō),元素 ID?在文檔中應(yīng)該是唯一的。
使用事件委派并使用數(shù)據(jù)屬性來(lái)識(shí)別應(yīng)激活刪除的按鈕。
document.addEventListener('click', evt => {
? const origin = evt.target;
? if (+origin.dataset.deleteparent) {
? ? origin.closest("li").remove();
? }
});
/*?
? --explained--
? const origin = evt.target;
? ? ? ? ? ? ? ? ?^ where did the click originated?
? if (+origin.dataset.deleteparent)
? ? ? ^? ? ? ?^ only if the button contains data-deleteparent attribute
? ? ? ^ convert data-attribute value to Number.?
? ? ? ? If it's not there, or 0, nothing will happen
? ? origin.closest("li").remove();
? ? ? ? ? ?^ parent li? ?^
? ? ? ? ? ? ? ? ? ? ? ? ?^ remove it
? }
*/
button[data-deleteparent] { color: red; border: none; background-color: transparent; cursor: pointer}
<h1>The List</h1>
<ul>
? <li>Delete me <button data-deleteparent="1">✘</button></li>
? <li>Delete me too <button data-deleteparent="1">✘</button></li>
? <li>Delete me not <button>Do not delete</button></li>
</ul>

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
只需使用 DOM 節(jié)點(diǎn)的屬性。 另外,如上所述 - 在你的情況下,你應(yīng)該使用 es 而不是 id,因?yàn)楸仨毷俏ㄒ坏摹arentElementclassid
const buttons = document.querySelectorAll('.rm-button');
function rmParent() {
this.parentElement.remove();
}
buttons.forEach(button => {
button.addEventListener('click', rmParent);
});
<h1>The List</h1>
<ul>
<li>Delete me<button class="rm-button">x</button></li>
<li>Delete me too<button class="rm-button">x</button></li>
</ul>
添加回答
舉報(bào)