我已经被困在这个问题上几个小时了,用谷歌搜索但仍然无法解决它。我会感谢一些指导,请伙计们。我在我正在处理的 php 项目中包含一个类似论坛的页面,用户可以在其中对帖子发表评论,然后提供对个人评论的回复。我的挑战在于代码的回复部分。我在评论后放置了一个回复按钮,点击后淡出以显示用户可以输入回复的文本区域。现在,当我单击回复按钮时,它会淡出,这没关系,但是文本区域会出现在帖子上的所有评论中。我尝试引入一个带有帖子 ID 值的数据属性(data-id)以将单击的回复按钮绑定到要显示的特定文本区域,但我似乎无法理解这一点。任何帮助将不胜感激。我的 PHP 代码在这里:
<?php
require("includes/conn.php");
$stmt=$conn->prepare("SELECT post_id, user, topic, post, time FROM post_tb ORDER BY time DESC");
$stmt->execute();
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
if ($num_of_rows > 0){
while ($row = $result->fetch_assoc()){
$post_id = $row['post_id'];
$user = $row['user'];
$topic = $row['topic'];
$post = $row['post'];
$time = $row['time'];
$time = date('M dS, Y g:i A', strtotime($time));
echo '<div>
<div>
<h5><strong>'.$user.'</strong></h5><h6>'.$time.'</h6>
<h5><strong>'.ucfirst($topic).'</strong></h5>
<p data-id="'.$post_id.'">'.$post.'</p>
</div>
<div>
<button type="button" class="btn btn-primary rep" id="but_rep" data-id="'.$post_id.'">Reply</button>
</div>
<form id="comment_reply" data-id="'.$post_id.'" method="post" action="">
<input type="hidden" class="hidden" value="'.$post_id.'" id="post_id">
<textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
<button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
</form>
<div/>';
}
}
?>
Run Code Online (Sandbox Code Playgroud)
和我的 jquery 在这里:
<script>
$(document).on('click', 'button#but_rep', function(e){
e.preventDefault();
var buttonId = $('form input#post_id').val();
//$('button#but_rep[data-id="buttonId"]').fadeOut();
//$('form#comment_reply[data-id="buttonId"]').fadeIn();
$(this).fadeOut();
$("form#post_comment_reply").fadeIn();
});
</script>
Run Code Online (Sandbox Code Playgroud)
无需使用data您可以使用的属性.closest()和.next()
$(document).on('click' , '.rep' , function(){
var closestDiv = $(this).closest('div'); // also you can use $(this).parent();
closestDiv.fadeOut();
closestDiv.next('form').show();
});
Run Code Online (Sandbox Code Playgroud)
注意:
id="but_rep",id="comment_reply"Id 必须是唯一的 .. 所以只对一个元素使用一个 id ..class=对更多元素使用
演示
$(document).on('click' , '.rep' , function(){
var closestDiv = $(this).closest('div'); // also you can use $(this).parent();
closestDiv.fadeOut();
closestDiv.next('form').show();
});
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function(){
$(document).on('click' , 'button.rep' , function(){
var closestDiv = $(this).closest('div'); // also you can use $(this).parent()
//closestDiv.fadeOut();
$('.comment_reply').not(closestDiv.next('.comment_reply')).hide();
//$('.rep').closest('div').not(closestDiv).show()
closestDiv.next('form.comment_reply').slideToggle(100);
});
});Run Code Online (Sandbox Code Playgroud)
form.comment_reply{
display: none;
}Run Code Online (Sandbox Code Playgroud)