【问题标题】:How to remove current row from table in jQuery?如何从jQuery中的表中删除当前行?
【发布时间】:2010-01-29 21:24:58
【问题描述】:

我有一个html表格如下

<table>
<tbody>
<tr>
<td>test content</td>
<td><input type="button" onClick="remove()"></td>
</tr>
....
...

</tbody>
</table>

现在,如果相同的模式继续存在,如果单击该行上的删除按钮,我想删除该行。我如何使用 jQuery 实现相同的功能?

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    更好:

    $(this).closest('tr').remove();
    

    More on closest()

    <input type="button" onClick="$(this).closest('tr').remove();">
    

    这样做的好处是无论您的 HTML 在单元格中是什么样子都可以正常工作。

    【讨论】:

      【解决方案2】:

      试试这个:

      <input type="button" onClick="$(this).parent().parent().remove();">
      

      或者您可以像这样使其更通用:

      <script>
        $(document).ready(function()
        {
          $(".btn").click(function(){
            $(this).parent().parent().remove();
          });
        });
      </script>
      
      <tr>
        <td><input type="button" class="btn"></td>
      </tr>
      

      【讨论】:

      • 可能想要使用类而不是 id。
      • 如果他想删除该行,我会在你的代码中包含一个“tr”,以防他添加更多元素,如 div。然后你的代码会中断,但@alt 的代码不会。
      猜你喜欢
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 2019-12-17
      • 2012-03-29
      • 1970-01-01
      相关资源
      最近更新 更多