jQuery删除表格行

24

我有一张桌子

<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函数,所以当用户点击删除时,该行的背景色将会改变,然后该行就会被删除。
$(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();
        });
    });
});

为什么只有背景发生了变化,但是行没有被删除?如何解决?

5个回答

59

当点击链接时,该行被删除,但由于点击链接会跳转页面,所以当页面刷新时它会立即恢复。

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

$(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仍将被找到。


你是什么意思?点击“删除”:行会逐渐消失然后被移除。 - Denys Séguret

3
您忘记在链接中设置哈希值。 例如:
<a class="deleteLink" href="" >delete</a>

应该是

<a class="deleteLink" href="#" >delete</a>

或者
return false;

在你的结尾处
$(document).ready(function() {
    $("#favoriteFoodTable .deleteLink").on("click",function() {
        ...
        return false;
    });
});

2
这里有另一个选项。
function DeleteRowOfProductTable(productID){
    $('#YourTableId tr').each(function (i, row) {
        var $row = $(row);
        var productLabelId =  $row.find('label[name*="Product_' + productID + '"]');

       var $productLabelIdValue = $productLabelId.text();
       if (parseInt(productID) == parseInt($productLabelIdValue))
       {
           $row.remove(); 
       }
    });
 }

0
如果您希望在表格中每次只能选择一行,请使用以下代码:
$("#data tr").click(function() {
    var selected = $(this).hasClass("highlight");
    $("#data tr").removeClass("highlight");
    if(!selected)
            $(this).addClass("highlight");

-1

尝试

var tr = $(this).closest('tr');
tr.detach();

对我来说很有效!


请在您的答案中添加更多描述 - Alex Filatov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接