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

时间:2018-12-25 12:57:02

标签: javascript html

如果单击HTML中的按钮,则它应搜索/找到下一个父级“表”元素,然后将其完全删除。我怎样才能做到这一点?请检查JS找出我已经测试过的内容。

我的HTML:

$query->statement('SELECT DISTINCT roomKey FROM tx_example_domain_model_room
                   WHERE startdatetime >= ? OR enddatetime <= ?', 
                   [$enddatetime, $startdatetime]);

我的JS:

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

2 个答案:

答案 0 :(得分:2)

使用closest

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

但是,您的HTML无效:table不能将divhr标记作为直接子代,因此table并不是按钮的父代。浏览器“修复”错误,并将所有那些无效的子元素移出table

仅当您使table结构有效的HTML时,此解决方案才有效。因此,它的任何子项都不应该是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>

答案 1 :(得分:0)

您正在寻找的是JQuery closest()函数。