2017-12-10 16 views
0

私のコメントセクションでユーザーが重複結果

私はアヤックス使用して更新する「の回答のショーの数を」必要なコメントを...答え、私のスクリプトは、まさにそのとき - 理由を除いて回答セクションはループ内に動的に作成され、すべての回答セクションのインスタンスを作成します。

Ex。 9と3コメント、27、23点の答えをそれぞれ

私が欲しいもの:

ユーザーはそれが今の答えの更新数を示す2
をコメントする答えを提出下(すなわち28)。私は何を得る2

コメント:

ユーザーが提出コメントへの回答2
これで、1つのコメントごとに更新された回答数が表示されるようになりました。コメント2

// comment 1 
9 answers 

// comment 2 
9 answers 
28 answers 
23 answers 
// after whole page refresh it goes back to just 
28 answers 

// comment 3 
23 answers 

私は私が欲しいものを得るために、私のセットアップや私のjQueryの負荷のいずれかをどのように修正すればよいの下で、それぞれ9、28、23)?

私の基本的なセットアップ:HTMLで
v.php(コメント付きページ)

<div id="commentAll"> 
    // loop to write all comment 
     <div id="answerAll"> 
      // answer textarea + button 
      // loop to write all answers to this comment 
       <div id="answerCount"> 
       <div id="answerShow"> 

// So it ends up looking like this 

<div id="commentAll"> 
    // comment 1 
     <div id="answerAll"> 
      // answer textarea + button 
      <div id="answerCount"> 
       9 answers 
      <div id="answerShow"> 
       // answer 1 
       // answer 2 
       . 
       . 
    // comment 2 
     <div id="answerAll"> 
      // answer textarea + button 
      <div id="answerCount"> 
       // before user has posted an answer 
       27 answers 
       // and after user has posted an answer 
       9 answers 
       28 answers 
       23 answers 
      <div id="answerShow"> 
       // answer 1 
       // answer 2 
       . 
       . 
    // comment 3 
     <div id="answerAll"> 
      // answer textarea + button 
      <div id="answerCount"> 
       23 answers 
      <div id="answerShow"> 
       // answer 1 
       // answer 2 
       . 
       . 

jQuery.js

var self = $(this); 
// Update database 
success:function(){ 
    var countAnswer = self.closest('#answerAll').find('[id^="answerCount"]'); 
    var showAnswer = self.closest('#answerAll').find('[id^="answerShow"]'); 
    countAnswer.load(location.href + " #answerCount>*", ""); 
    showAnswer.load(location.href + " #answerShow>*", ""); 
    closestDiv.find('textarea').val('') ; 
} 

答えて

0

IDパラメータは一意である必要があります。コメント3には<div id="answerCount3"></div>のような一意のIDを使用するようにhtmlを設定する必要があります。この方法で特定の要素にアクセスしてコンテンツを更新することができます。例えば ​​- あなたのAPIの呼び出しは、このような答えの数が返された場合 -

[1: "9 answers",2: "28 answers", 3: "23 answers"]

を、あなたのHTMLを更新するには、次のjQueryコードを使用することができます。

// given that result contains [1: "9 answers",2: "28 answers", 3: "23 answers"] 
$.each(result, function(key, value) { 
    $("#answerCount"+key).html(value); 
}