基于if条件的jQuery DataTables columnDefs

时间:2019-03-13 17:07:38

标签: javascript jquery datatables

在DataTables的columnDefs中,如果条件语句可以执行吗?根据变量值,我们决定在下面显示/隐藏哪一列。 我该如何解决以下问题? 下面的代码抛出此错误:

  

未捕获的SyntaxError:如果出现意外令牌

"columnDefs": [
        if (operation == Operation.VIEW) {
            {"targets": [0], "className": "text-center"},
            {"targets": [1], "className": "text-center"},
            {"targets": [2], "width": "3%", "visible": false}
        }
        if (operation == Operation.EDIT) {
            {"targets": [0], "className": "text-center"},
            {"targets": [1], "width": "3%", "visible": false},
            {"targets": [2], "className": "text-center"}
        }
    ],

1 个答案:

答案 0 :(得分:0)

请遵循以下语法和代码来实现您的逻辑

"columnDefs" : [ {
                            "targets" : [ 3, 4, 5 ],
                            render : function(data, type, row, meta) {
                                if (meta.col == 4) {
                                    if (data == 1) {
                                        return 'Test1';
                                    } else if (data == 2) {
                                        return 'Test2';
                                    }
                                } else if (meta.col == 3 || meta.col == 5) {

                                    if (data == null || data == "") {
                                        return "";
                                    } else {
                                        return data;
                                    }
                                }
                            },
                        } ],


"columnDefs" : [ {
                            "className" : "dt-center",
                            "targets" : "0"
                        } ],