简体   繁体   中英

Find a div inside another div using $this and .find

I have multiple comment forms on one page and after an ajax call need to append the comment to the commentsholder div. But currently its adding it to all, Not sure how to go about only adding it to the current div.

So the comments section looks like this:

<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>

The jQuery append:

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

There are other forms etc inside the comments divs, but what i need to do is only append the comment to the comments holder that is in the currently in use commentson div.

如果this上下文是addcommentbutton,请尝试此操作

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

this context depends upon where you are trying to do this operation. if you are doing it within the ajax call ( after an ajax call need to append the comment ) back you could do something like this.

 $('.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(...);
        }
     });

 });

All you have to do is add the parent and child in the jQuery selector:

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

But if you have multiple .commentsholder then you can use:

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

$(this) being the current clicked "Button"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM