首页 > 解决方案 > 获取所选数据表行的 id 并将其传递给用于多行删除的函数

问题描述

我得到的代码几乎可以满足我的要求

<script> $(document).ready(function() {
    var table=$('#dataTable').DataTable();
    $('#dataTable tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    }
    );
    $('#button').click( function () {
        alert( table.rows('.selected').data().length +' row(s) selected');
    }
    );
}

);
</script>
<button type="button" id="button">select all</button>

它显示在 alert(); 选择了多少行。但我想要它做的是获取表第一列中的 id 并通过此函数将其传递给删除

function confirmRemove(id) {
    if (id) {
        $.ajax( {
            url: "product-delete.php", type: "post", data: {
                id_delete: id
            }
            , success:function(response) {
                var productTable=$("#dataTable").DataTable();
                productTable.ajax.reload(null, false);
                swal( {
                    title: "SUCCESS!", text: "Product Deleted!", icon: "success", timer: 1800, button: false,
                }
                );
            }
            , error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        }
        );
        return false;
    }
}

标签: javascriptdatatable

解决方案


您必须遍历数据表selected行并获取第一列并将其传递给您的confirmRemove函数。下面的代码做到了:

$('#button').click(function () {

     var data = table.rows('.selected').data();
     data.each(function (value, index) {
     //call the delete function
     confirmRemove(value[0]);
     });
}

推荐阅读