I've already saw Event binding on dynamically created elements? before asking this question but I still don't know why I cannot find a elements from AJAX and don't know how to write the code best way without need to duplicate the whole bind content
I've added the following script to my site (I'm using jQuery 1.11.1):
$().ready(function() {
$('a:not(.flags a)').filter(function() {
return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');
$(document).on('click', '.internal_link', function(e) {
var url = $(this).attr('href');
$.ajax({
url: url,
dataType: 'json',
data: "{}",
success: function(data) {
document.title = data.meta_title;
$('#articlecontent').fadeOut(400, function()
{
$(this).fadeOut('slow').html(data.content).fadeIn('slow');
});
// It seems that this filter doesn't work
$('#articlecontent a').filter(function() {
return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');
// should I write here code to made AJAX links to have click method?
$('nav li a').removeClass('selected');
$('#nav_'+data.code).addClass('selected');
$('meta[name=keywords]').attr('keywords', data.meta_keys);
$('meta[name=description]').attr('description', data.meta_desc);
}
});
e.preventDefault(); // stop the browser from following the link
});
});
It finds links with the same hostname and add them class internal_link and then for elements with internal_link class it binds onclick action - data are loaded via AJAX.
But the problem appears when data loaded also have links. I would like also for them do the same thing - find links and add them internal_link class (I've already done it but it seems that filter for AJAX content in this case doesn't work) and bind them onclick action but I don't know how to do this. But the problem is that in fact I have to do the same as I already done in my code. Should I have add the whole bind function itself in success again or there is some way to reuse the function one again?
Question: how to achieve this result and is this AJAX secure? I don't have much experience in AJAX and don't know is it safe to load into #articlecontent any data from AJAX request.