jQuery删除表行 [英] jquery delete table row

查看:103
本文介绍了jQuery删除表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子

<table id="favoriteFoodTable">
    <th>
        Food Name:
    </th>
    <th>
        Restaurant Name:
    </th>
    <th>

    </th>
    <?php while ($row = $foods->fetch()) {
        ?>
        <tr>
            <td>
                <?php echo $row['foodName']; ?>
            </td>
            <td>
                <?php echo $row['restaurantName']; ?>
            </td>
            <td>
                <a class="deleteLink" href="" >delete</a>
            </td>
        </tr>
    <?php } ?>
</table>

我使用此jquery函数,因此当用户单击删除时,行的背景将更改,然后行将删除

I use this jquery function so when a user click on delete, the background of the row will change and the row then will delete

$(document).ready(function() {
    $("#favoriteFoodTable .deleteLink").on("click",function() {
        var td = $(this).parent();
        var tr = td.parent();
        //change the background color to red before removing
        tr.css("background-color","#FF3700");

        tr.fadeOut(400, function(){
            tr.remove();
        });
    });
});

只是背景在变化,但该行没有被删除,为什么?该怎么解决?

just the background is changing but the row is not deleted, why? how to solve?

推荐答案

该行将被删除,但是随着单击使您跟随链接,刷新页面后会立即将其恢复.

The row is deleted but as clicking makes you follow the link, it's immediately restored when the page is refreshed.

在回调的末尾添加return false; event.preventDefault(); ,以防止出现默认行为:

Add return false; or event.preventDefault(); at the end of the callback to prevent the default behavior :

$(document).ready(function() {
    $("#favoriteFoodTable .deleteLink").on("click",function() {
        var tr = $(this).closest('tr');
        tr.css("background-color","#FF3700");
        tr.fadeOut(400, function(){
            tr.remove();
        });
        return false;
    });
});

演示

请注意,我使用closest编写了更可靠的代码:如果在两者之间插入另一个元素,则仍会找到tr.

Note that I used closest for a more reliable code : if another element comes in between, the tr will still be found.

这篇关于jQuery删除表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆