如何将 ajax 调用返回的数据附加到一个动态创建的 div,它位于许多具有相同“类名”的 div 中?
我的 HTML:
<div class="post_area">
<?php
$connObj = new Connection();
$conn = $connObj->getConnection();
$sql = ("select * from posts ");
$result = mysqli_query($conn, $sql);
if ( $result ) {
echo "<br><br>";
$rowcount = mysqli_num_rows($result);
for($i = 0; $i<$rowcount; $i++){
$row = mysqli_fetch_assoc($result);
?>
<h3>
<?php
echo $row['title']."<br>";
?>
</h3>
<?php
echo $row['description']."<br>";
?>
<div class="post_comments">
<div class="comments_only_box" id="cb">
//displaying comments dynamically
</div>
</div>
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="<?php echo $present_id; ?>">
</div>
<?php $present_id = $row['id']; ?>
我的 ajax 调用:
<script>
$(document).ready(function () {
$(".comm").on('click', function () {
var id = $(this).data('id');
var comment = "helloworld";//example
$.ajax({
url: 'comment.php',
method: 'GET',
data: {
comment: comment,
id: id,
},
dataType: 'html',
success: function (data) {
console.log(data);
$('#cb').append(data);
}
});
});
});
</script>
当我追加数据时,它被追加到所有 div——但我只想将它追加到当前单击的 div
最佳答案
当有人点击您的 comment
按钮时,点击处理程序会收到对该特定元素的引用作为 this
。由于该按钮位于 div
内,您可以使用 closest
找到包含该按钮的 div
,然后更新该 div
。例如:
$(".comm").on("click", function() {
var $div = $(this).closest("div.post_area");
// Do something with `$div`...
});
实例:
$(".comm").on("click", function() {
var $div = $(this).closest("div.post_area");
var $input = $div.find("input[name=comment]");
var comment = $input.val();
$("<p>").text(comment).appendTo($div);
$input.val("").focus();
});
.post_area {
border: 1px solid #ddd;
height: 6em;
overflow: auto;
}
<p>Type in any of the comment boxes and click the button following it:</p>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 如何将从 ajax 调用返回的数据附加到动态创建的 div,在许多具有相同类名的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989327/