i have this method, that does some ajax and with the result makes a new div before a div and then inserts the ajax response in it. The problem i have is while using on('click') my second click appends a new div before the previously created div(what i want) but also creates another div after(not what i want) that is exactly the same.
AJAX/jQuery:
$(document).on('click', '.ajaxcommentbutton1', function() {
var currentDiv, pageValue, newPage, newPageid;
currentDiv = $(this).attr('group');
pageValue = parseFloat($(this).attr('data'));
newPage = pageValue + 1;
newPageid = '.' + newPage;
$.ajax({url:"comments.php",
type:'POST',
dataType:'text',
data: {id: currentDiv,
page: newPage},
success:function(result){
$('div[data="' + currentDiv + '"] .commentsContainer > div').before("<div class='" + newPage + "'> </div>");
$('div[data="' + currentDiv + '"] ' + newPageid).html(result);
$('button[group="' + currentDiv + '"]').attr('data', newPage);
$('button[group="' + currentDiv + '"]').off();
}});
});
HTML Result of first click:
<div class='commentsContaier'>
<div class="2">stuff in here</div>
<div class="1">stuff in here</div>
</div>
HTML Result of second click (BAD ONE):
<div class='commentsContaier'>
<div class="3">stuff in here</div>
<div class="2">stuff in here</div>
<div class="3">stuff in here</div>
<div class="1">stuff in here</div>
</div>
Because $('div[data="' + currentDiv + '"] .commentsContainer > div')
matches every <div>
under your container, and .before()
will add your AJAX content into every matched <div>
, duplicating your AJAX content.
i.e. in the second click, the new element is inserted into both <div class="1">stuff in here</div>
and <div class="2">stuff in here</div>
Try replace it with $('div[data="' + currentDiv + '"] .commentsContainer > div:first-child')
to match only the first child of all the <div>
s, with the :first-child
selector