0

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?

1
  • If purpose of this question is just to seek improvements in your working code, codereview.stackexchange.com is the right place for it. Commented Jan 30, 2016 at 6:14

1 Answer 1

2

I think it would go something like this:

$("table").each(function(){
  var filename = $(this).data("filename");
  var this1 = $(this);
  $.getJSON(filename,function(data){
    this1.html(renderTriangle(data['ActiveCustomers']));
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm, this doesn't seem to work. filename is undefined (but I'm certain it's set in the HTML). If I change every $(t) to $(this), filename gets set correctly but then I get the error Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
where did you define the document.createDocumentFragment??
Bingo. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.