如何在div内的特定点上添加内容

时间:2015-08-04 11:21:56

标签: javascript jquery html

假设我有一个带有id(主要评论)的div以及更多带有回复ID的div。我想在回复结束时动态添加评论的内容。我无法获取最后一个回复的ID,但我可以获取主要评论的ID(这也是评论框的ID,它总是在最后。这样的事情:

<div class="commentArea">
<div class="comment_'.id.'"> Something </div>
<div class="reply_'.replyid.'"> What kind of comment is that? </div>
<div class="reply_'.replyid.'"> What kind of reply is that? </div>
<div class="reply_'.replyid.'"> You guys are strange. </div>
<div class="replyToComment_'.id.'"> some button and stuff </div>
</div>

我想在replyToComment _&#39; .id。&#39;之前在commentArea中添加内容。 ...

我有一个想法可能有效并且看起来像这样(我想也许有一些更容易的方法)。

<div class="commentArea">
<div class="comment_'.id.'"> Something </div>
<div class="reply_'.replyid.'"> What kind of comment is that? </div>
<div class="reply_'.replyid.'"> What kind of reply is that? </div>
<div class="reply_'.replyid.'"> You guys are strange. </div>
<div class="newReply"></div>
<div class="replyToComment_'.id.'"> some button and stuff </div>
</div>

只需在发布的每个回复结尾处添加并清空newReply的div ...

还有其他想法吗?

4 个答案:

答案 0 :(得分:0)

.jpendTo()是你需要的:

http://api.jquery.com/appendto/

答案 1 :(得分:0)

我不确定,我理解你的问题,但我认为.prepend()可以帮到你。

您需要将最后一个div(即<div class="replyToComment_'.id.'"> some button and stuff </div>)与其他div包装在一起,并且每次都对该父级执行.prepend()。像这样:

<div class='parentContainer'>
<div class="replyToComment_'.id.'"> some button and stuff </div>
</div>

每次都要$(".parentContainer'").prepend(newComment)添加评论。

答案 2 :(得分:0)

好的我想到了实现这一目标的几种方法......“如果我理解你要问的是什么”

通过这种方式你甚至不需要使用ID作为一个类....除非有特定的理由这个?!?! 如果没有,那么将id移动到id属性并给它这样的

id="2,56" 
2 = the question || post id
56 = the answer id
通过这种方式,您可以更好地控制帖子和评论

1. if reply_ is an individual class

    $('.reply_')[$('.reply_').length - 1].after(comment);

2. if replyToComment_ is an individual class

    $('.replyToComment_').before(comment);

答案 3 :(得分:0)

我就是这样做的:

$("#addtxt").click(function () {
    $("[class^='replyToComment']").before("<div class='newReply'>" + $("#text").val() + "</div>");
});

Here is the JSFiddle demo