This is related to Click event doesn't work on dynamically generated elements
Basically I tried to expand a collapsed blockquote upon click
replyfix($('#element'));//In the original data, the expander works as intented
$.ajax({
url : pageurl,
success : function (source) {
$('#element').after(replyfix($(source).find('#element')));
}
});
function replyfix(reply){
reply.find('blockquote blockquote').addClass('collapsed').append('<a href="javascript:;" class="expander">click</a>').children('div').hide();
reply.find('.expander').one('click', function(){
$(this).parent().find('div').show();
$(this).parent().find('.expander').remove();
});
return reply;
}
My question is that the object should already be created in the ajax request, and that I bind the new data every time they are created. Why would direct binding not work?
At first I thought I did something wrong in my code, so I tried to confirm I binded an event on the newly created object using
console.log($._data(reply.find('.expander')[0], "events"));
and it shows that the new expander already got an click event binded.
update: The above code is what I have used before, that I would like to understand why it won't work.
$('#element').on('click', ".expander", function(){
$(this).parent().find('div').show();
$(this).parent().find('.expander').remove();
});
has already solved the problem.