当前位置: 动力学知识库 > 问答 > 编程问答 >

creating tables with ids with jquery and json

问题描述:

I am trying to build an html-table with jquery. The data I am going to use is coming from a json-file. By now I am using a specific json-file per row. i. e. "adressen1.json", "adressen2.json" and so on.

Is it possible to merge these json-files?

When a row is created a button will be created, too. On click on this button the data of this row is displayed in second place. Unfortunately is does not work for me. Perhaps I am missing something.

Thank you for your support in advance.

Here is the HTML-code:

<div id="area_test">

<table class="testtable_head">

<tr>

<th> Button </th>

<th> Name </th>

<th> PLZ </th>

<th> Ort </th>

<th> Land </th>

<th> Referenz </th>

<th> Gesperrt </th>

</tr>

<tbody class="testtable_body">

</tbody>

</table>

<div id="json_2">

</div>

</div>

Here is the jQuery-code and the json-file:

$( document ).ready(function() {

$.getJSON( "js/adressen1.json", function( data ) {

$(".testtable_body").append("<tr><td><button id='test_1'>JSON</button></td><td>" + data.Name + "</td> <td>" + data.postleitzahl + "</td><td>" + data.Ort + "</td><td>" + data.Land + "</td><td>" + data.Referenz + "</td><td>" + data.Sperre + "</td></tr>");

});

$( "#test_1" ).click(function() {

$.getJSON( "js/adressen1.json", function( data ) {

$("#json_2").append(data.Vorname + " " + data.Name + "<br>" data.postleitzahl + " " + data.Ort);

});

});

{

"an": "Herrn",

"Titel": "Dr.",

"Vorname": "Klaus",

"Name": "Meier",

"Zusatz": "",

"Strasse": "Goldstraße 56",

"postleitzahl": "78966",

"Ort": "Berlin",

"Land": "DE",

"Info": "",

"Kurzname": "KM",

"Sperre": "Offene Rechnung",

"Referenz": ""

}

网友答案:

Sure you can. Simply add all rows to array

[
    {"an": "Herrn", "Titel": "Dr."}, 

    {"an": "Herrn", "Titel": "Dr."}
]

And use a loop to process data

$.getJSON( "js/adressen1.json", function( data ) {
    var html = "";
    data.forEach(function(item, idx){
        html += "<tr><td><button data-id=" + idx+ ">JSON</button></td><td>" + data.Name + "</td>   <td>" + data.postleitzahl + "</td><td>" + data.Ort + "</td><td>" + data.Land + "</td><td>" + data.Referenz +  "</td><td>" + data.Sperre + "</td></tr>"    
    });
    $(".testtable_body")
        .append(html)
        .on('click', 'button[data-id]', function(){
            var item = data[$(this).data('id')];
            $("#json_2").append(item.Vorname + " " + item.Name + "<br>" item.postleitzahl + " " + item.Ort);
    });
}); 
分享给朋友:
您可能感兴趣的文章:
随机阅读: