如果destroy设置为true,则数据表中的排序箭头会出现多次

时间:2015-06-26 10:57:36

标签: javascript datatable

我需要在每次点击提交按钮时重新初始化我的数据表。我设置destroy : true来实现这一目标。但每次数据表重新初始化时,每列显示的排序箭头数量会增加1。我怎样才能防止这种情况发生?这是我的javascript代码。每次用户点击提交时,都会调用processFormData,在验证表单字段后调用initializeDataTable。

var firstName = "";
var lastName = "";
var country = "";

$(document).ready(function() {
    $('#userDetails').dataTable();
});

function processFormData() {

    firstName = document.userDetailsTable.firstName.value;
    lastName = document.userDetailsTable.lastName.value;
    country = document.userDetailsTable.country.value;

    if (document.userDetailsTable.firstName.value == ""
            || document.userDetailsTable.lastName.value == ""
            || document.userDetailsTable.country.value == "") {
        bootbox.alert("Please fill in all fields!");
    } else {

        initializeDataTable();
    }
    return false;
}

function initializeDataTable() {

    $('#userDetailsTable').dataTable({
                "destroy" : true,
        "pageLength" : 12,
        "processing" : true,
        "serverSide" : true,
        "ajax" : {
            "url" : '/fetchSearchResults',
            "type" : 'POST',
            "data" : {
                "length" : 12,
                "formFirstName" : firstName,
                "formLastName" : lastName,
                "formCountry" : country
            }
        }
    });

};

1 个答案:

答案 0 :(得分:0)

看来您使用delete选项的方法应该在理论上有用。因此,如果不知道我们是否可能有不同的设置,我就不会尝试重现这一点。相反,我建议使用 ajax.reload()与更新的ajax.data一起运行,以更新当前保存在表格中的数据。 可能的代码调整将如下所示:

function initializeDataTable() {
    return $('#userDetailsTable').dataTable({
            "destroy" : true,
        "pageLength" : 12,
        "processing" : true,
        "serverSide" : true,
        "ajax" : {
            "url" : '/fetchSearchResults',
            "type" : 'POST',
            "data" : {
                "length" : 12,
                "formFirstName" : firstName,
                "formLastName" : lastName,
                "formCountry" : country
            }
        }
    });
};

var processFormData = (function(){
    var table = null;
    return function(){
        var firstName = document.userDetailsTable.firstName.value;
        var lastName = document.userDetailsTable.lastName.value;
        var country = document.userDetailsTable.country.value;

        if (firstName == "" || lastName == "" || country == "") {
            bootbox.alert("Please fill in all fields!");
        } else if (table !== null) {
            table.ajax.data.firstName = firstName;
            table.ajax.data.lastName = lastName;
            table.ajax.data.country = country;
            table.ajax.reload();
        } else {
            table = initializeDataTable();
        }
    };
})();

调用processFormData()不应该为您提供更新的表格。我虽然没有测试过此代码。