jQuery Selection & Filtering Problem
Greetings,
I am trying to append a new comment to a Comments UL, in a string of parent po开发者_如何学Pythonsts, using jQuery. I cannot seem to figure out how to append to the parent post's comments UL, here is the HTML -
<div class="statusUpdate-DIV">
<div class="statusUpdate-middle">
<span class="statusUpdate-timestamp"><?php echo date("M d, y g:i a", strtotime($row['timestamp']));?></span>
<span class="statusUpdate-title"><?php echo $row['title'];?></span>
<?php echo $row['body'];?>
<div class="commentsDIV" id="status<?php echo $row['id'];?>">
<ul class="commentsBlock">
<li><strong>This is a comment</strong> comment here</li>
</ul>
</div>
<div class="postCommentDIV">
<span class="commentHeader">Comment</span>
<form name="commentForm" class="postCommentFORM" method="post" action="">
<textarea rows="3" cols="63" class="commentBody" name="commentBody"></textarea>
<input type="submit" value="Post"/>
</form>
</div>
</div>
</div>
I am trying to append the value of commentBody
(form textarea) to commentsBlock
(UL). I was able to retrieve the value of commentBody
with the following script, issue is appending it to the previous commentsBlock UL:
//This is just a test to make sure the value of .commentBody is being retrieved
$(".postCommentDIV form").submit(function() {
var comment = $(this).find(".commentBody").val();
alert(comment);
return false;
});
Thanks..
All you need is to add this where the alert currently is:
// Create the <li> containing the comment
var commentLi = $("<li>").text(comment);
// Travel up DOM tree to the closest statusUpdate-DIV, then back down to append
$(this).closest("statusUpdate-DIV").find(".commentsBlock").append(commentLi);
jQuery's .text()
will automatically escape any HTML in the comment.
$(this).closest('.statusUpdate-middle').find('.commentsBlock').append(comment);
- the
closest()
(docs) method to get the neareststatusUpdate-middle
ancestor - the
find()
(docs) method to find the nestedcommentsBlock
- the
append()
(docs) method to append the comment.
I think you should do something like this:
$(".postCommentDIV form").submit(function() {
var comment = $(this).find(".commentBody").val();
$('<li>').text(comment).appendTo('.commentsDIV .commentsBlock');
return false;
});
Pay attention in using class for performance issues, better to use id to identify a unique block, as the containing the comments, so you could do .appendTo('#commentsBlock').
try:
$(".postCommentDIV form").submit(function() {
var comment = $(this).find(".commentBody").val();
$(this).find(".commentsBlock").append("<ul><strong>" + comment + "</strong></ul>");
return false;
});
精彩评论