简体   繁体   English

动态创建jQuery-jTable的多级Javascript对象

[英]Dynamic creation of multilevel Javascript object for jQuery-jTable

jTable (jTable.org) layout is defined by the code below. jTable(jTable.org)布局由下面的代码定义。 I want to build it dynamically (based on AJAX return from a database query). 我想动态构建它(基于从数据库查询返回的AJAX)。

{
    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? 我可以动态修改上面的字段部分吗? eg, to have four pivot columns with relevant column titles. 例如,要有四个带有相关列标题的透视列。

Answer 回答

I figured it out thanks to Barmar and extensive reading. 感谢Barmar和广泛的阅读,我想通了。 The trick is to insert a new object at each level. 诀窍是在每个级别插入一个新对象。 Pop this into jsfiddle.net and you can see the result. 将其弹出到jsfiddle.net中,您可以看到结果。 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));

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: 但是如果你正在修改表,你可以简单地销毁旧的jTable并重新初始化它:

$("#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之前,您需要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM