简体   繁体   English

JS-如何从按钮单击事件中查找特定元素TAG以将其删除?

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

If a button in my HTML is clicked, it should search / find the next parent 'table' element and delete it completly. 如果单击我HTML中的按钮,则它应搜索/找到下一个父级“表”元素并完全删除它。 How can I do that? 我怎样才能做到这一点? Please check JS to find out what I have already test it. 请检查JS找出我已经测试过的内容。

My HTML: 我的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>

My JS: 我的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....

});

Use closest : 使用closest

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

However, your HTML is not valid: table cannot have div or hr tags as direct children, and so the table is not really the parent of the button. 但是,您的HTML无效: table不能将divhr标记作为直接子代,因此该table并不是按钮的父级。 Browsers "fix" the error, and move all those invalid child elements out of the table . 浏览器“修复”错误,并将所有那些无效的子元素移出table

This solution will only work if you make your table structure valid HTML. 仅当您使table结构为有效的HTML时,此解决方案才有效。 So, no children of it should be div . 因此,它的div都不应该是div

For instance: 例如:

 $(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