2013-07-14 46 views
5

Tôi đang cố đăng nhận xét bằng bài đăng AJAX. Nhưng phần tử comment mới nhất chứa nút gửi. Và sau khi thêm, mục mới sẽ xuất hiện sau khi gửi nút.Nối phần tử không kết thúc, trước phần tử cuối cùng trong jQuery

<div class="commentContainer" > 

    <div class="comment"> 
     <div class="commentText">Any comment1 ... </div> 
    </div> 

    <div class="comment"> 
     <div class="commentText">Any comment2 ... </div> 
    </div> 
     .................................... 
    <div class="comment"> 
     <div class="sendPanel"> 
      <input type="submit" value="Post" /> 
     </div> 
    </div> 

</div> 

và kết quả của việc đăng yêu cầu:

success: function (result) { 
    if (result.success) { 
     $('.commentContainer').append('<div class="comment"><div class="commentText">' + result.text + '</div></div>'); 
    } 
} 

tôi muốn giữ nút gửi vào cuối luôn. Tôi có thể làm cái này như thế nào?

+0

Cảm ơn tất cả sự giúp đỡ. –

Trả lời

4

Hãy thử điều này

$('<div class="comment"><div class="commentText">' + result.text + '</div></div>') 
    .insertBefore('commentContainer .comment:last-child'); 

Hoặc thậm chí tốt hơn

$('<div>', {'class': 'comment'}).append(
    $('<div>', {'class': 'commentText', text: result.text}) 
).insertBefore('.commentContainer .comment:last-child'); 

Cái này là tốt hơn cho hiệu suất

Demo

jQuery last-child

jQuery insertBefore

1

Hãy thử điều này:

success: function (result) 
    { 
     if (result.success) 
     { 
      $('<div class="comment"><div class="commentText">' + result.text + '</div></div>').insertBefore('.commentContainer .comment:last'); 
     } 
    } 
2

Bạn có thể sử dụng: cuối cùng pseudo-selector:
thử điều này:

success: function (result)  
    { 
        if (result.success)  
        { 
            $('.commentContainer').find('div:last').before('<div class="comment"><div class="commentText">' + result.text + '</div></div>'); 
        }    
    } 
Các vấn đề liên quan