单击上面的按钮删除元素

时间:2015-09-24 18:49:36

标签: javascript jquery html

我使用Jquery将表行添加到现有表中。我的添加有两列。一个简单的字符串,另一个有一个小按钮。我想点击按钮以最优雅的方式删除其父元素,理想情况下不需要调用外部JS函数。有可能吗?

2 个答案:

答案 0 :(得分:3)

只需在按钮的点击处理程序中使用.closest.remove

jQuery(this).closest('tr').remove()

closest将找到与传递的选择器匹配的最接近的父元素,顾名思义remove将删除它。

由于您说要将行添加到现有表中,因此您可以使用委派来处理新行,而不必在每次添加新行时添加新的单击侦听器。

jQuery(document).on("click",".removeBtn",function(){
   jQuery(this).closest('tr').remove()
});

演示

jQuery(".removeBtn").click(function(){
  jQuery(this).closest("tr").remove();  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Sample row</td>
    <td><button class="removeBtn">Remove</button></td>
  </tr>
  <tr>
    <td>Sample row 2</td>
    <td><button class="removeBtn">Remove</button></td>
  </tr>
  <tr>
    <td>Sample row 3</td>
    <td><button class="removeBtn">Remove</button></td>
  </tr>
</table>

答案 1 :(得分:0)

&#13;
&#13;
$(document).ready(function() {
  $(document).on('click', '.remove', function() {
    $(this).closest('tr').remove();
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>
        This is Item 1
      </td>
      <td>
        This is still Item 1
      </td>
      <td>
        <button class="remove">This is Button 1</button>
      </td>
    </tr>
    <tr>
      <td>
        This is Item 2
      </td>
      <td>
        This is still Item 2
      </td>
      <td>
        <button class="remove">This is Button 2</button>
      </td>
    </tr>
    <tr>
      <td>
        This is Item 3
      </td>
      <td>
        This is still Item 3
      </td>
      <td>
        <button class="remove">This is Button 3</button>
      </td>
    </tr>
    <tr>
      <td>
        This is Item 4
      </td>
      <td>
        This is still Item 4
      </td>
      <td>
        <button class="remove">This is Button 4</button>
      </td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;