P
P
Platon Fedorovich2015-10-02 13:16:13
JavaScript
Platon Fedorovich, 2015-10-02 13:16:13

How in jQuery to track the asynchronous creation of a new element in the document and add a response from the function to it?

Greetings.
I apologize in advance for the clumsy question, but I do not know how else to ask. Let me tell you better with an example.
I have a script that has this function:

var myFunc= function() {
  // В файле response.json находится обычный JSON,
  // для примера вот такой: {"one":"1","two":"2","three":"3"}
  $.getJSON('data/response.json', function(data) {
    $('span.counter').text(data.one);
  });
};

Also, the script has the ability to add an element (something like a ToDo list in terms of functionality):
$(function() {
  $('#add').on('click', function(event) {
    event.preventDefault();
    $('<a href="#" class="my-class">Element <span class="counter"></span></a>').appendTo('#result');
  });
});

Question: how to track the creation of a new element (after clicking on the button with id="add") and add a response to it from the function myFunc()? So just update the $.getJSON file request for this new element and not for all that were created earlier?
ADD:
Solution https://jsfiddle.net/730xnkzr/#run

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
littleguga, 2015-10-02
@platon_fedorovich

$(function() {
  $('#add').on('click', function(event) {
    event.preventDefault();
    $('<a href="#" class="my-class">Element <span class="counter"></span></a>').appendTo('#result');
    myFunc();
  });
});

What doesn't fit?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question