我试图在单击按钮时删除父级。
<div class="image">
<img src="" alt="First">
<button id="one" class="remove" onclick="removeThis('one');">X</button>
</div>
<script>
function removeThis(_this){
alert("hello" + _this);
$(_this).parents.remove();
};
</script>
这不起作用
整个代码:
<!DOCTYPE html>
<html>
<body>
<script>
function registerClickHandler () {
// Implement the click handler here for button of class 'remove'
}
function removeThis(_this){
alert("hello" + _this);
// $('#' + _this).parents().remove();
_this.parentNode.parentNode.removeChild( _this.parentNode );
};
</script>
<div class="image">
<img src="" alt="First">
<button id="one" class="remove" onclick="removeThis('one');">X</button>
</div>
<div class="image">
<img src="" alt="Second">
<button id="second" class="remove" onclick="registerClickHandler()">X</button>
</div>
</body>
</html>
最佳答案
您没有调用 parents()
方法
替换
$(_this).parents.remove();
与
$(_this).parents().remove();
或者根据你的情况
$(_this).parent().remove();
由于您的问题中没有包含 jquery
标签,因此您也可以使用以下普通 js
_this.parentNode.parentNode.removeChild( _this.parentNode );
您还需要将此引用传递给此方法调用
<button id="one" class="remove" onclick="removeThis(this);">X</button>
根据您更新的代码,尝试将方法更改为此
function removeThis(_this){
var el = document.getElementById( _this.id ); //assuming '_this' is the 'this' reference not the 'id'
el.parentNode.parentNode.removeChild( el.parentNode );
};
关于javascript 如何从 onclick 中删除父 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46339986/