I've just read some threads about using on()
to attach events to dynamically created html elements. I came up with this example (FIDDLE) to try to bind the click
event to elements div.clicktitle
returned via AJAX. The div elements have data attributes from which the click event should get the values and then display them. But It doesn't seem to be working.
What is working for me is to define the click
event function and put it in the Ajax success callback. (FIDDLE) Is that the only way to make the click event to work with AJAX returned elements? Can anyone tell me why .on()
isn't attaching the event to div.clicktitle
?
HTML before Ajax
<div class="main"></div>
<div class="second"></div>
After Ajax it should be
<div class="main"><div data-source="Hello" class="clicktitle"><h6>Title1</h6></div></div>
<div class="second"><div data-source="Hello" class="clicktitle"><h6>Title2</h6></div></div>
JS Code:
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22https%3A%2F%2Fnews.google.com%2F%3Foutput%3Drss%22&format=json&diagnostics=true&callback=",
success: function (data) {
var length = 0;
var items = data.query.results.item;
items = items.map(function(item){
return '<div data-source="Hello" class="clicktitle"><h6 style="background:beige;">'+item.title+'</h6></div>';
});
var half = items.length/2;
for(var i = 0; i < items.length; i++)
if(i < half)
$('.main').append(items[i]);
else
$('.second').append(items[i]);
length++;
},
error: function () {}
});
$('.clicktitle').on("click",function(){
var datasource = $(this).data('source');
$(this).text(datasource);
});