This question has already been answered:

I load the data with the get method and "insert" it in $ .each

$.each(data.dialogs, function(){ var html = ''; html += '<li data-id="'+ this.id +'" class="im_dialogs">'; html += '<a href="#'+ this.id +'">'; html += ' <div class="dialogsEachImg"><img src="/uploads/users/'+ this.avatar +'" alt=""></div>'; html += '<div class="dialogsEachLogin">'+ this.login +'</div>'; html += '<div class="dialogsEachMessage">'+ this.message +'</div>'; html += '</a>'; html += '</li>'; $('.dialogsEach').append(html); }); 

.dialogsEach is <ul>

Then, I need to track clicks on these elements (there may be a bunch of them), read the data-id and transfer to the server.
The problem is reading ID, I just can not.
As I understand it, the problem is that due to the fact that I use append , I need to read it differently (most likely).
Tried to find a solution in Google, but the golyak. Get out.
UPD: If I specify a class that is dynamically created, then when clicking instead of the specified URL, favicon.ico loads

Reported as a duplicate by Grundy members, aleksandr barakin , user207618, user194374, Duck Learns to Take Cover September 5 '16 at 6:40 pm .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • I tried - it does not roll. If I specify a class that is created dynamically, then when you click instead of the specified URL, favicon.ico is loaded - DeadMoras

1 answer 1

If I correctly understood the question.

 $("#addData").click(function() { var data = {}; data.dialogs = [{ id: 1, name: "first" }, { id: 2, name: "second" }, { id: 3, name: "three" }] $.each(data.dialogs, function() { var html = ''; html += '<li data-id="' + this.id + '" class="im_dialogs">'; html += this.name; html += '</li>'; $('.dialogsEach').append(html); }); }); $(".dialogsEach").on("click", ".im_dialogs", function() { var x = $(this).attr("data-id"); $("span").append(x) }) 
 .im_dialogs { list-style: none; cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="addData">add Data</button> <ul class="dialogsEach"> </ul> <span></span>