简体   繁体   中英

Generate table width dynamic json Data

I create a plugin Generate grid, and data is json string.

            var objGrid = { 
                "tbody": [
                    { "stt": "1", "name": "Le Nguyen Nhat Bang", "description": "Vinh Long" },
                    { "stt": "2", "name": "Dang Truong Chinh", "description": "Binh Dinh" },
                    { "stt": "3", "name": "Cu Ngoc Sang", "description": "Dak Lak" }
                ]
            }

    (function ($) {
                $.fn.generateGrid = function (data) {
                    this.append("<table>");

                    var tbody = $('<tbody>');
                    $("table", this).append(tbody);
                    if (data != null && data.tbody != null) {
                        for (var j = 0; j < data.tbody.length; j++) {
                            $(tbody).append('<tr>').children('tr:last')
                            .append($("<td>").append(data.tbody[j]....))
                            .append($("<td>").append(data.tbody[j]....))
                            .append($("<td>").append(data.tbody[j]....));
                        }
                    }
                }

            } (jQuery));

 $(document).ready(function () {
            $("#grid").generateGrid(objGrid);
        });

I want to generate dynamic table follow json data. Now it's just has three fields, another day i want 4 or 5 fields but not change code in plugin. Thanks

Try this. Use each method to loop for each property of json for appending td. So how many properties will be there it will add that much td.

(function ($) {
            $.fn.generateGrid = function (gridTitle, data) {
                this.append("<table>");

                var tbody = $('<tbody>');
                $("table", this).append(tbody);
                if (data != null && data.tbody != null) {
                    for (var j = 0; j < data.tbody.length; j++) {
                    var trContent=   data.tbody[j],
                        trElm=$('<tr />') 



                    $.each(trContent,function(k,v){
                        trElm.append('<td>'+v+'</td>');
                    });

                    $(tbody).append(trElm);   
                    }
                }
            }

        } (jQuery));

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