代码之家  ›  专栏  ›  技术社区  ›  Adi Sembiring

使用jquery删除行表

  •  5
  • Adi Sembiring  · 技术社区  · 15 年前

    假设我有这样一张桌子

    id  name    address     action
    --------------------------------------
    s1  n1  a1      delete
    s2  n2  a2      delete
    

    例如,删除就是一个链接 <a href="http://localhost/student/delete/1"> . 在实际情况中,我使用Ajax删除了学生。为了简化代码,我只是提醒链接并省略Ajax脚本。我只想知道如何使用jquery从HTML文档中删除行。

    $(document).ready(function() {
    $("a").click(function(event) {
        alert("As you can see, the link no longer took you to jquery.com");
            var href = $(this).attr('href');
            alert(href);
            event.preventDefault();
       });
    );
    

    我希望,当我通知链接后,所选行将自动删除。有没有什么建议如何实施这个?

    3 回复  |  直到 7 年前
        1
  •  17
  •   Philippe Leybaert    15 年前

    不需要调用PreventDefault()。简单地从事件处理程序返回false具有相同的效果。

    删除 <a> 链接已定位,您可以调用$(this).closest(“tr”).remove():

    $(document).ready(function() {
    $("a").click(function(event) {
        alert("As you can see, the link no longer took you to jquery.com");
        var href = $(this).attr('href');
        alert(href);
        $(this).closest("tr").remove(); // remove row
        return false; // prevents default behavior
       });
    );
    
        2
  •  1
  •   psychotik    15 年前

    为每个添加一个ID <tr> 打电话 row_9714 并添加ID 9714 链接。然后在Click事件处理程序调用中:

    var thisId = $(this).attr('id');
    $("#row_" + thisId).remove();
    

    注意--9714只是一个虚拟的ID。只需在这里为每一行使用一个唯一的数字。

        3
  •  0
  •   Fellipe    7 年前

    此示例使用jquery从表中删除行。

    $(document).ready(function () {
    $("#my_table .remove_row").click(function () {
    	$(this).parents("tr:first")[0].remove();
    });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table"  border="1" id="my_table">
       <tbody>
          <tr>
             <td>1</td>
             <td>1</td>
             <td>1</td>
             <td><button type="button" class="remove_row">X</button></td>
          </tr>
          <tr>
             <td>2</td>
             <td>2</td>
             <td>2</td>
             <td><button type="button" class="remove_row">X</button></td>
          </tr>
       </tbody>
    </table>