2011-08-24 55 views
1

正在爲web應用程序創建評論系統時,評論在用戶點擊評論圖片時加載,html代碼是用json動態生成以顯示評論。 但再次單擊圖像時,該請求被再次提出用相同的數據確定元素是否存在

填充頁面下面有我的代碼

function latest_pheeds() { 
    var action = url+"pheeds/latest_pheeds"; 
    $.getJSON(action,function(data) { 
     $.each(data,function(index,item) { 
      $('#pheed-stream').append 
      (
      '<div class="pheed" id="'+item.pheed_id+'">'+ 
      '<p><a href="">'+item.user_id+'</a></p>'+ 
      '<p>'+item.pheed+'</p>'+ 
      '<div class="pheed_meta">'+ 
      '<span>'+item.datetime+' Ago</span>'+ 
      '<span>'+item.comments+ 
      '<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+ 
      '</span>'+ 
      '</div>'+ 
      '</div>' 
      ); 
     }); 
    }); 
} 



function retrieve_comments(pheed_id) { 
    var action = url+'comments/get_comments'; 
    var crsf = $('input[name=ci_csrf_token]').val(); 
    var dataString = "pheed_id="+pheed_id+"&ci_csrf_token="+crsf; 
    $.ajax({ 
     url:action, 
     type:'POST', 
     cache:false, 
     dataType:'json', 
     data:dataString, 
     success:function(data) { 
      $.each(data,function(index,item) { 
       $("#" + pheed_id).append(
       '<div class="pheed_comments">'+ 
        '<div class="comment">' 
        +'<span><p>'+item.user+'</p></span>' 
        +item.comment+ 
        '</div>'+ 
       '</div>'+ 
       '<div id="comment_box">'+ 
        '<textarea id="comment" cols="30">'+ 
        '</textarea><br>'+ 
        '<input type="button" class="submit_btn" value="comment" />'+ 
       '</div>' 
       ); 
      }); 
     } 
    }); 
} 

latest_pheeds()加載pheeds和retrieve_comments獲得通過pheed_id的意見到它。 我如何確定評論區域是否已經被填充,並且如果可用,則用新評論更新它。由於

回答

3

檢查

$("#" + pheed_id +' .pheed_comments').length 

如果爲0,如果該元素(我猜意思VOU div.pheed_comments)不存在。

+0

我會盡力謝謝 – MrFoh

2

幾種選擇:

1)如果你已經從你的Ajax調用所有的評論,然後刪除你從DOM有以前的意見,並插入你剛剛得到的一切。

2)如果你有一個ajax調用只能檢索新的評論,那麼你可以檢查DOM,看看你是否已經在DOM中有評論,然後在一些令牌之後請求新評論(即你以前會保存)。當你收到新的評論時,你可以將它們附加到你所擁有的內容上。

$('#pheed-stream').children().length會告訴您在pheed-stream層次中有多少個孩子。如果這是零,你還沒有做過任何的調味。

我會建議,最簡單的方法是檢索所有評論,並用新評論列表替換所有內容,而不是嘗試檢索新評論。僅檢索新評論需要某種時間標記,您可以向服務器提供這些標記,以便知道哪些「新評論」可以爲您提供幫助。

$("#" + pheed_id + " .pheed_comments").length會告訴你是否有任何評論已經被檢索到,但是該pheed_id。

1

您正在添加ID與ID。只要檢查它是否存在。如果是,則更新它,否則插入。