javascript 如何从 onclick 中删除父 div

标签 javascript

我试图在单击按钮时删除父级。

<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/

相关文章:

javascript - 从下拉框中获取选定的值并用于填充文本框 php javascript

javascript - JS 对象字面量中的方法和子方法

javascript - 如何结合 window.location.href 和 DOMContentLoaded

javascript - 如何在 jQuery 函数中传递数组或添加循环

javascript - react 上下文的问题

javascript - 根据关键字查找特定元素并推送到数组

Javascript 连接数字,而不是相加

javascript - ASP.net/Javascript : Automatically postback triggering and next control to have focus

javascript - 将 Ember.js 与 Sock.js 结合使用

javascript - 检测滚动方向