使用 jQuery 和 PHP 的回复集成评论系统

Comment system with reply integration using jQuery & PHP

我目前正在做一个评论系统项目。我可以写评论,将其保存到我的数据库中,然后将其取回并显示在网页上。但是当我在我现有的评论系统之上加入回复评论功能时,我遇到了麻烦。问题 1:我在每个评论 div 下创建了 2 个新的可点击对象,首先是 'no.of replys',它显示了新的回复。第二个是 'reply now',这是一个供用户回复该评论的文本区域。但是,当我单击其中任何一个时,所有可单击项都会在评论的其余部分 div 中打开,而不仅仅是我正在单击的那个。问题 2:我只能在最近的评论 div 上回复并将我的回复发送到数据库。当我尝试回复较早的评论时,页面会自行刷新,并且没有任何内容记录到数据库中。以下是我的标记。如果这令人困惑,我很抱歉,但英语不是我的母语。如有任何意见,我们将不胜感激。

<div class="timeline">

    <?php $stmt = $DB->query("CALL get_comment($aid)");
      $results = $stmt->fetchAll(); $stmt->closeCursor();
      foreach ($results as $info) {
      ?>

        <div class="commentBox">
            //The comment markup

             <p class="allreplys">Replys</p> //This opens all replys
             <p class="replyButton">Reply me</p> //This opens reply form

           <form class="replySection">
           //The reply form markup
           </form>

          <div class="replyTimeline">
            <?php
               $stmt = $DB->query<"CALL get_reply('$aid','$pid')");
               $replys = $stmt->fetchAll(); $stmt->closeCursor();
               foreach ($replys as $re) {
               ?>
                    <div class="replyBox>
                      //Reply Markups
                    </div>
               <?php } ?> //Close of reply foreach
           </div> //Close of replyTimeline

       </div> //Close of commentBox

   <?php } ?> //Close of comment foreach

</div> //Close of timeline

以下是我的 jQuery 标记

$(document).ready(function() {
    $('.allreplys').click(function(event) {
       $('.replyline').toggle();
    });
    $('.replyButton').click(function(event) {
       $('.replySection').toggle();
    });
});

这个效果更好吗?

我的目的是缩小您正在使用的选择器的范围,该选择器当前选择整个页面中具有 class 名称 "allreplys" 或 "replyButton" 的所有元素。通过使用 $(this).parent(".commentBox").find(...

$(this) 指的是被点击的按钮,在本例中是一个 p 标签。 "parent(...)" 向上导航节点树以到达具有 class 名称“.commentBox”的标签,并且 find(...) 将使用该节点内给定的选择器及其 children(以及它们的 children 等等(递归))。希望只切换一项而不是全部。

尽管我在您的代码中没有看到一个名为 "replyline" 的 class,所以这可能是一个失败点。

$(document).ready(function() {
    $('.allreplys').click(function(event) {
       $(this).parent(".commentBox").find(".replyline").toggle();
    });
    $('.replyButton').click(function(event) {
       $(this).parent(".commentBox").find(".replySection").toggle();
    });
});