动态创建jQuery-jTable的多级Javascript对象 [英] Dynamic creation of multilevel Javascript object for jQuery-jTable

查看:97
本文介绍了动态创建jQuery-jTable的多级Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jTable(jTable.org)布局由下面的代码定义。我想动态构建它(基于从数据库查询返回的AJAX)。

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.

答案

感谢Barmar和广泛的阅读,我想通了。诀窍是在每个级别插入一个新对象。将其弹出到jsfiddle.net中,您可以看到结果。它将以编程方式创建上面的对象。

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));


推荐答案

我没有看到改变字段的方法规范动态。但是如果你正在修改表格,你可以简单地销毁旧的jTable并重新初始化它:

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: {}
};

在初始化jtable之前,你需要:

Before you initialize a jtable, you do:

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

这篇关于动态创建jQuery-jTable的多级Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆