簡體   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