Dynamic creation of multilevel Javascript object for jQuery-jTable

試著忘記壹切 提交于 2019-12-06 04:06:19

问题


jTable (jTable.org) layout is defined by the code below. I want to build it dynamically (based on AJAX return from a database query).

{
    title: 'My Dynamic Title',
    fields: {
        id: {
            title: 'ID'
        },
        salesperson: {
            title: 'Salesperson'
        },
        pivot1: {
            title: '2012-01'
        },
        pivot2: {
            title: '2012-02'
        },
        pivot3: {
            title: '2012-03'
        }
    }
}    

The data being displayed is a pivot table and so the number of columns and their titles will change. Is it possible for me to dynamically modify the fields section above? e.g., to have four pivot columns with relevant column titles.

Answer

I figured it out thanks to Barmar and extensive reading. The trick is to insert a new object at each level. Pop this into jsfiddle.net and you can see the result. It will programmatically create the object above.

var myobj = {}; //description for jquery-jtable configuration.
var colnames = ['pivot1', 'pivot2', 'pivot3'];
var titles   = ['2012-01', '2012-02', '2012-03'];

myobj['title'] = "My Dynamic Title";
myobj['fields'] = {};                     //create a second level under 'fields'.
myobj.fields['id'] = {title: 'ID'};
myobj.fields['salesperson'] = {title: 'Salesperson'};
for(i = 0; i < colnames.length; i++) {
    myobj.fields[colnames[i]] = {};       //create a third level under column name.
    myobj.fields[colnames[i]].title = titles[i];
}
alert(JSON.stringify(myobj, null, 4));

回答1:


I don't see a method to change the field specification dynamically. But if you're modifying the table, you can simply destroy the old jTable and reinitialize it:

$("#TableContainer").jtable("destroy");
$("#TableContainer").jtable({
    // New options
});

If there are some options that will stay consistent across all instances, you can use a variable to hold the options:

var jtable_options = {
    title: "My Table Title",
    fields: {}
};

Before you initialize a jtable, you do:

jtable_options.fields = {
    id: { title: 'ID' },
    salesperson: { title: 'Salesperson' }
    ...
};
$("#TableContainer").jtable(jtable_options);


来源:https://stackoverflow.com/questions/18800609/dynamic-creation-of-multilevel-javascript-object-for-jquery-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!