2017-08-04 70 views
0

我試圖創建一個用戶可以回答現有問題的問題/答案系統。問題系統正確發佈並顯示到數據庫,但我在回答動態創建的問題時遇到困難。使用AJAX目標和更新動態創建的內容

要保存在這裏的空間是沒有

$(document).ready(function() { 
//make sure it was the postReply button 
    $("#postReply").on("click", function(){ 
     //get the questionID the user just clicked on 
     var questionID=$(this).val(); 
     //hide the reply button 
     $("#postReply").hide(); 
     //show the reply framework 
     $('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>'); 
    }); 
}); 

一個循環內從該行調用代碼:

echo '<p><button type="submit" id="postReply" value='.$questionID.'>Reply</button></p> '; 
echo '<div class="reply" id="reply'.$questionID.'">'; 

,我打的問題是,我更新和增加股利到每一個問題,因爲.reply是不正確的目標。我似乎無法讓它定位到被點擊的問題ID。我試着用警報進行測試,但只有最近的問題按鈕正在解析到腳本中。

我只能隱藏最近添加的評論按鈕。

這是正在從SQL查詢

<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p> 
<p><button type="submit" id="postReply" value=34>Reply</button></p> 
<div class="reply" id="reply34"></div> 

創建時點擊回覆按鈕對上述問題的代碼應該看起來像HTML源代碼的輸出:

<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p> 
<div class="reply" id="reply34"> 
    <div class="replycontent"> 
     <p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p> 
     <p><button id="postAnswer" type="submit">Post Answer</button></p> 
    </div> 
</div> 

回答

1

我不確定是否真的明白了這個問題,但請嘗試替換:

$('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>'); 

由此:

$('#reply' + questionID).append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>'); 

您的字段有所有不同的ID屬性,因此您可以使用它。

要隱藏您的按鈕,因爲它們具有相同的ID,您的選擇器可能看起來像$('#postRelpy[value="' + questionID + '"]')

+1

謝謝@iArcadia我不得不編輯一些HTML,我把它弄糟了,但是在你的幫助下把它們都放在正確的位置! – Ben