如何改进这个加载JSON文件的javascript代码更加动态

时间:2016-01-30 05:31:31

标签: javascript jquery html json

我正在构建一个包含html表集合的网页。每个表的数据都存储了JSON文件,我编写了一个JQuery方法来加载数据并将其呈现为HTML。目前,这看起来像

HTML
<!-- Load sample_triangles.json into the following table -->
<table class="table json-triangle" data-filename="data/sample_triangles.json"></table>

<!-- Load sample_triangles2.json into the following table -->
<table class="table json-triangle" data-filename="data/sample_triangles2.json"></table>


JQuery
function renderTriangle(tri){
    //Renders a single triangle object to HTML (assumed to be wrapped inside <table> </table>)
    ...
    return str_tbl;
};

$.getJSON('data/sample_triangles.json', function(data){
  $('table[data-filename="data/sample_triangles.json"]').html(renderTriangle(data['ActiveCustomers']));
});

$.getJSON('data/sample_triangles2.json', function(data){
  $('table[data-filename="data/sample_triangles2.json"]').html(renderTriangle(data['ActiveCustomers']));
});

如何更好地概括此代码,以便只创建一个带有<table>属性的data-filename元素将触发JQuery搜索具有给定文件名的json文件并尝试在表中呈现它?

1 个答案:

答案 0 :(得分:2)

我认为它会是这样的:

$("table").each(function(){
  var filename = $(this).data("filename");
  var this1 = $(this);
  $.getJSON(filename,function(data){
    this1.html(renderTriangle(data['ActiveCustomers']));
  });
});