我正在开发一个带有评论框的网页,人们可以使用该评论框进行评论,这些评论使用 AJAX 动态显示在同一页面上。例如,当您提交评论时,它会发布在之前的评论之上。
这是我在 AJAX 中所做的事情:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var newDivElement = document.createElement('form');
newDivElement.setAttribute('id',"postForm");
newDivElement.setAttribute('action',"updateRecords.php");
newDivElement.setAttribute('method',"post");
newDivElement.innerHTML=postContent;
document.getElementById('mainPostContainer').appendChild(newDivElement);
}
}
(postcontent
由一个包含评论的 div 组成)
现在,如果我连续发表两条评论,说“这是第 1 条评论”和“这是第 2 条评论”,它们会按以下顺序发布:
<div id=mainPostContainer>
<form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 1st comment </div></form>
<form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 2nd comment </div></form>
</div>
但我希望它们按以下顺序排列:
<div id=mainPostContainer>
<form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 2nd comment </div></form>
<form id="postForm" action="updateRecords.php" method="post"><div id="post"> this is 1st comment </div></form>
</div>
我尝试使用insertBefore()
而不是追加,但我不知道如何获取前一个元素(即最后创建的<form>
)。
我在这里做错了吗?还是有更好的方法来做我想做的事情?也许使用jQuery?
编辑:我正在使用<form>
,因为表单中有按钮和文本类型的输入元素,我没有提到它们只是为了保持简单。