[英]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
不能将div
或hr
标记作为直接子代,因此该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.