繁体   English   中英

javascript如何从onclick删除父div

[英]javascript how can I remove a parent div from onclick

单击按钮时,我正在尝试删除父项。

<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 );
};

如果使用的是jQuery,请更改为:

$(_this).parents.remove();

$("#" + _this).parents().remove();

如果您使用的是香草JS,请更改为以下内容:

<div class="image">
    <img src="" alt="First">
    <button id="one" class="remove" onclick="removeThis(this);">X</button>
</div>

function removeThis(ele) {
    ele.parentNode.remove();
};

您已经使用#来使用button id选择器,因此其工作正常

 function removeThis(_this) { alert("hello" + _this); $('#' + _this).parent().remove(); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="image"> <img src="" alt="First"> <button id="one" class="remove" onclick="removeThis('one');">X</button> </div> 

<div class="image" ID="DivParent">
  <img src="" alt="First">
  <button id="one" class="remove" onclick="removeThis();">X</button>
</div>
<script>
function removeThis(this){
    $("#DivParent").hide();
};
</script>

在您的代码中尝试一下

  1. parents()代替parents 引用JQuery DOM
  2. 如果您仍在加载Jquery,请充分利用它(例如click event

     <div class="image"> <img src="" alt="First"> <button id="one" class="remove">X</button> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#one").click(function() { alert("Test"); $("#one").parent().remove(); }); }); </script> 

如果只想删除前一个立即元素,则可以使用prev()来完成。

像这样=> $("#one").prev().remove();

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM