jquery 是否可以根据数据属性删除表行

ldfqzlk8  于 2022-12-12  发布在  jQuery
关注(0)|答案(3)|浏览(138)

On Click of delete button is it possible to remove the table row based on the data attribute ?
This is my js code

$(document).on("click", ".deletevideo", function(event) {
    if (confirm("Are You Sure to Remove This Video From This PAC?") == true) {
        var video_id = $(this).data('videoid');
    }

    event.stopImmediatePropagation();
    event.preventDefault();
    return false;
});

Fiddle

hpxqektj

hpxqektj1#

您可以使用closest()遍历需要删除的最多tr元素。

if (confirm("Are You Sure to Remove This Video From This PAC?")) {
    //Travese up to get the row and delete
    $(this).closest('tr').remove();
}

Fiddle

ymdaylpp

ymdaylpp2#

You need to pass the Index of the tr for which you want the data-attribute from

$('#tableid tr:eq(0)'); // First row in table

$('#tableid tr:eq(1)'); // Second row in table

Because there might be multiple rows in the table

var theRowId = $('#tableid tr:eq(1)').attr('data-id'); // Get the Second Row id
$('#tableid tr#'+theRowId).remove();  // Remove the row with id

OR if you know the ID of the Row.. simply do this

$('#tableid tr[data-id="'+theRowId+'"]').remove();
nbysray5

nbysray53#

Adding my two cents following @Satpal's solution.
If anyone using Fetch API then this (Delete) sample might help too.
HTML (Thymeleaf in my case):

<td><a class="btn btn-sm btn-danger" th:onclick="deletedbfile([[${myfile.id}]], this);">Delete</a></td>

JavaScript:

function deletedbfile(id, Object) {
    fetch('/deletedbfile/' + id, {
        method: 'DELETE',
    })
        .then((response) => {
            //alert(response.status);
            if (response.status == 204) {
                Object.closest('tr').remove();
            }
            console.log('Success:', response);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
}

相关问题