简体   繁体   中英

Passing dynamic values to plugin function jquery

I am using the JSONTable plugin and trying to pass values to the 'head' and 'json', dynamically, by taking them from an array object. For example I could load a new json file convert it to js object and read the fresh 'head' and 'json' attributes.

$("#dataTable").jsonTable({
    head : ['#','Operating System','Market Share'],
    json : ['id', 'name', 'share']
});

I faced similar problems while using other plugins. I know this should be a very obvious thing, but haven't been able to figure out how to do this. I have tried passing the entire function in a string, but that renders it into a string and not a function object. Any help will be appreciated. thanks!

You can read the properties of the first item in the array and use them as column names ( here is a test):

HTML:

<textarea id="data" cols="60" rows="10">[
{"id" : 1, "name" : "iOS", "share" : 57.56},
{"id" : 2, "name" : "Android", "share" : 24.66},
{"id" : 3, "name" : "Java ME", "share" : 10.72},
{"id" : 4, "name" : "Symbian", "share" : 2.49},
{"id" : 4, "name" : "Blackberry", "share" : 2.26},
{"id" : 4, "name" : "Windows Phone", "share" : 1.33}
]</textarea><br />
<input type="button" id="fillButton" value="Fill table" /><br/>
<table id="dataTable"></table>

JavaScript:

function fillTable(tableId, jsonString) {
    var data = JSON.parse(jsonString),
        dataColumn, dataColumns = [];

    if(!(data instanceof Array) || data.length === 0)
        return;
    for (dataColumn in data[0])
        if (data[0].hasOwnProperty(dataColumn))
            dataColumns.push(dataColumn);
    $("#" + tableId)
        .html("<table id='" + tableId + "'><thead></thead><tbody></tbody></table>")
        .jsonTable({
            head: dataColumns,
            json: dataColumns,
        })
        .jsonTableUpdate({
            source: data
        });
}

$("#fillButton").click(function () {
    fillTable("dataTable", $("#data").val());
});

Result:

id    name            share
1     iOS             57.56
2     Android         24.66
3     Java ME         10.72
4     Symbian         2.49
4     Blackberry      2.26
4     Windows Phone   1.33

Try changing data values in the <textarea> and press the button. You can change column names only when the names are changed everywhere in the JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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