我正在尝试创建一个输入标记列表以及旁边的删除按钮。当我点击删除按钮时,它旁边的输入标签也应该被删除。此处只有按钮被删除,但不是相应的let cursor = captionTextView.cursorOffset!
。我该怎么做?
li
答案 0 :(得分:1)
将项目父项用于.removeChild
。
var deleteButtons = document.querySelectorAll(".delete-button");
var grandparent;
for (var i = 0; i < deleteButtons.length; i++) {
deleteButtons[i].addEventListener('click',function(e){
grandparent = e.target.parentElement.parentElement;
grandparent.removeChild(e.target.parentElement);
});
}
<ul>
<li>
Test Test 1<button class="delete-button">Delete</button>
</li>
<li>
Test Test 2<button class="delete-button">Delete</button>
</li>
<li>
Test Test 3<button class="delete-button">Delete</button>
</li>
<li>
Test Test 4<button class="delete-button">Delete</button>
</li>
<li>
Test Test 5<button class="delete-button">Delete</button>
</li>
</ul>
答案 1 :(得分:1)
你得到parentNode
,Element
继承自Node
:
在ES5中
document.querySelectorAll(".deleteButton").forEach(function(btn) {
//Add listener for click event on delete button
btn.addEventListener('click', function(e) {
//it will always return the li tag
//beucase lit tag is parent of button..
e.target.parentNode.remove();
});
});
&#13;
<ul>
<li>Coffee<button class="deleteButton">Delete</button></li>
<li>Tea <button class="deleteButton">Delete</button></li>
<li>Milk <button class="deleteButton">Delete</button></li>
</ul>
&#13;
在ES6中
document.querySelectorAll(".deleteButton").forEach(btn => {
//Add listener for click event on delete button
btn.addEventListener('click', e => e.target.parentNode.remove());
});
&#13;
<ul>
<li>Coffee<button class="deleteButton">Delete</button></li>
<li>Tea <button class="deleteButton">Delete</button></li>
<li>Milk <button class="deleteButton">Delete</button></li>
</ul>
&#13;
<强>参考文献:强>