我正在尝试用简单的JavaScript学习我以前在jQuery中做过的事情。
我有一个例子,我在互联网上找到了解决它真的给了我很多时间。
点击div.single
时,我想删除父button.remove
。
这是代码;
var btn = document.getElementsByClassName('remove')
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click',function (e) {
e.parentNode.parentNode.removeChild(e.parentNode);
} , false);
}
&#13;
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X1</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X2</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X3</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X4</button>
</div>
&#13;
我收到错误e.parentNode is undefined
。
这是我所追求的jQuery代码。
$(document).ready(function() {
$(document).on('click', '.remove', function () {
$(this).parent('.single').remove()
})
})
感谢您的回答。
答案 0 :(得分:5)
您需要从事件对象(currentTarget / target)获取元素引用
注意:所有现代浏览器都支持Node.remove()
var btn = document.getElementsByClassName('remove')
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function(e) {
e.currentTarget.parentNode.remove();
//this.closest('.single').remove() // in modern browsers in complex dom structure
//this.parentNode.remove(); //this refers to the current target element
//e.target.parentNode.parentNode.removeChild(e.target.parentNode);
}, false);
}
&#13;
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X1</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X2</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X3</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X4</button>
</div>
&#13;
答案 1 :(得分:1)
要以较短的方式删除父节点:
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" onclick="return this.parentNode.remove();" class="remove">X</button>
</div>
答案 2 :(得分:1)
如果您使用的是ES6 and above,则可以避免为点击事件使用currentTarget
:
const removeButtons = document.getElementsByClassName('remove');
Array.from(removeButtons).forEach((removeButton) => {
removeButton.addEventListener('click', () => {
removeButton.parentNode.remove();
});
});
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X1</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X2</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X3</button>
</div>
<div class="single">
<img src="http://via.placeholder.com/150x150">
<button type="button" class="remove">X4</button>
</div>
答案 3 :(得分:0)
this.parentElement.remove也可以工作