I
I
Ilya Loopashko2020-01-23 13:44:59
JavaScript
Ilya Loopashko, 2020-01-23 13:44:59

How to use the script once instead of pasting it every time?

I have a script:

$.getJSON('/js/db04.json', function (data) {
    $(data).each(function(index, item) {
    $('#table').append(
        '<tr><td class="col1">'+ item.title01 +'</td><td class="col2">' + item.shopcode + '</td><td> <a href="' + item.link + '">' + item.title + '</a></td><td class="col3">' + item.cost + '</td></tr>'
        );
    });
});

It gets data from a JSON file, I have a lot of such files, how to modify it so that this code is not inserted for each data file, but used once.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Athanor, 2020-01-23
@deadloop

Take it to a separate function and pass the necessary parameters, which can change from call to call as arguments.

function getJsonAndUpdateTable(jsonPath) {
  $.getJSON(jsonPath, function (data) {
      $(data).each(function(index, item) {
      $('#table').append(
          '<tr><td class="col1">'+ item.title01 +'</td><td class="col2">' + item.shopcode + '</td><td> <a href="' + item.link + '">' + item.title + '</a></td><td class="col3">' + item.cost + '</td></tr>'
          );
      });
  });
}

And then call this function where necessary and pass inside the path to the desired json file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question