【问题标题】:Find a div inside another div using $this and .find使用 $this 和 .find 在另一个 div 中查找 div
【发布时间】:2014-04-06 18:14:51
【问题描述】:

我在一页上有多个评论表单,在 ajax 调用后需要将评论附加到 cmetsholder div。但目前它把它添加到所有,不知道如何只将它添加到当前的 div。

所以 cmets 部分如下所示:

<div class="commentson">
<div class="commentsholder"> All THE COMMENTS IN HERE </div>
    <form class="addcomment" action="process/addcomment.php" method="post">
        <div class="commentbutton">
        <input type="text" maxlength="250" name="addpostcomment" class="addpostcomment" placeholder="Add Comment... (max 60 characters)" />
        <input type="submit" id="addcommentbutton" class="addcommentbutton" value="Post" disabled/>
        </div>
        <span class="countdownCommentLength"></span>
    </form>
</div>

jQuery 追加:

$( ".commentsholder" ).append("New Comment");

cmets div 内还有其他形式等,但我需要做的只是将注释附加到当前使用的 cmetson div 中的 cmets 持有人。

【问题讨论】:

  • 你的整个 html 结构是什么样的?
  • 什么决定了“当前的 div”
  • 刚刚用完整的 html 更新了问题。我所说的当前 div 是指包含已提交表单的 div。

标签: javascript jquery html ajax append


【解决方案1】:

您所要做的就是在 jQuery 选择器中添加父项和子项:

$( ".commentson .commentsholder" ).append("New Comment");

但是如果你有多个 .cmetsholder 那么你可以使用:

$(this).parent(".commentsholder ").append("New Comment");

$(this) 是当前点击的“按钮”

【讨论】:

    【解决方案2】:

    如果this 上下文是添加评论按钮,请尝试此操作

    $(this).closest('form').prev().append($(this).siblings('.addpostcomment').val());
    

    【讨论】:

      【解决方案3】:

      this 上下文取决于您尝试执行此操作的位置。如果您在 ajax 调用 (after an ajax call need to append the comment) 中执行此操作,则可以执行以下操作。

       $('.addcommentbutton').click(function(){
           var $this = $(this); //cache it here
      
           //your ajax call
           $.ajax({
              ....
              success: function(){
                 $this.closest('.addcomment').prev().append(newComment);
                 //or
                 //$this.closest('.commentson').find('.commentsholder').append(...);
              }
           });
      
       });
      

      【讨论】:

      • 完美,谢谢!我会做一个笔记,以更深入地研究使用 this/closest/prev/find 等移动 div 等。有点混乱。
      • @user2921557 欢迎您。 :) 在旁注中,请将您的 js 代码也放在问题中,这将避免人们试图理解您的问题的猜测工作.. :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多