I'm building a web page with a collection of html tables. The data for each table is stored JSON files and I wrote a JQuery method to load the data and render it into HTML. Currently, this looks like
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']));
});
How can I generalize this code better so that simply creating a <table> element with a data-filename attribute will trigger JQuery to search for a json file with the given filename and attempt to render it in the table?