2014-02-15 46 views
0

我有這種方法,做一些AJAX和結果使一個div之前新的div,然後在其中插入ajax響應。我的問題是在使用('點擊')時,我的第二次點擊在先前創建的div之前追加了一個新的div(我想要的),但也創建了另一個div(而不是我想要的),完全相同。jQuery點擊使用.before()

AJAX/jQuery的:

<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> 

回答

0

因爲$('div[data="' + currentDiv + '"] .commentsContainer > div')<div>匹配:第二次點擊(BAD ONE)的

<div class='commentsContaier'> 
    <div class="2">stuff in here</div> 
    <div class="1">stuff in here</div> 
</div> 

HTML結果:第一次點擊的

$(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 + "'>&nbsp</div>"); 
     $('div[data="' + currentDiv + '"] ' + newPageid).html(result); 
     $('button[group="' + currentDiv + '"]').attr('data', newPage); 
     $('button[group="' + currentDiv + '"]').off(); 
    }}); 
}); 

HTML結果在您的容器下,並且.before()將添加您的將AJAX內容複製到每個匹配的<div>,複製您的AJAX內容。

即在第二次點擊,新元素被插入到兩個<div class="1">stuff in here</div><div class="2">stuff in here</div>

嘗試用$('div[data="' + currentDiv + '"] .commentsContainer > div:first-child')取代它僅匹配所有<div> S的第一個孩子,與:first-child選擇

+0

謝謝!豎起大拇指 – donny5561