簡體   English   中英

JS-如何從按鈕單擊事件中查找特定元素TAG以將其刪除?

[英]JS - How to find specific element TAG from a button click event to remove it?

如果單擊我HTML中的按鈕,則它應搜索/找到下一個父級“表”元素並完全刪除它。 我怎樣才能做到這一點? 請檢查JS找出我已經測試過的內容。

我的HTML:

 <table class="table table-bordered">            
    <!-- OTHER HTML CODE with div etc. DONT REMOVE/TOUCH THIS! -->
</table>


 <table class="table table-bordered"> <!-- THIS table element should delete, if the button is clicked -->
    <hr class="my-4 border-dark" id="hereWeGo">
    <div class="row">
      <div class="col-auto justify-content-around d-flex flex-column border">
        <button type="button" class="remove btn btn-danger" id="RemoveBtn">Remove</button>
      </div>
      <div class="col border">
        <B>Title...</B><br />
        <hr class="my-1">
        Link...
      </div>
    </div>
  </table>



 <table class="table table-bordered">            
    <!-- OTHER HTML CODE with div etc. DONT REMOVE/TOUCH THIS! -->
</table>

我的JS:

$(document).on('click', '.remove', function() {
//$(this).parents('table').remove();
//alert("im here");
//$(this).parents('table').remove();
//alert($(this).parents('hr').html()); 
//$('div.row').remove();

// after this is run, it should remove the <table class="table table-bordered"> element....

});

使用closest

$(this).closest("table").remove();

但是,您的HTML無效: table不能將divhr標記作為直接子代,因此該table並不是按鈕的父級。 瀏覽器“修復”錯誤,並將所有那些無效的子元素移出table

僅當您使table結構為有效的HTML時,此解決方案才有效。 因此,它的div都不應該是div

例如:

 $(document).on('click', '.remove', function() { $(this).closest("table").remove(); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <hr class="my-4 border-dark" id="hereWeGo"> <table class="table table-bordered"> <!-- THIS table element should delete, if the button is clicked --> <tr class="row"> <td class="col-auto justify-content-around d-flex flex-column border"> <button type="button" class="remove btn btn-danger" id="RemoveBtn">Remove</button> </td> <td class="col border"> <B>Title...</B><br /> <hr class="my-1"> Link... </td> </tr> </table> 

您正在尋找的是JQuery closest()函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM