2016-03-06 53 views
1

我一直在使用php和jQuery的注释系统。我使用jQuery来滑动窗体,只要按下回复键,而只有2个按钮只适用于一种窗体。如何停止打开jquery中的同一个div标签的2个按钮

我正在使用php从mysql数据库获取数据,并在div标签中显示它显示的内容,并在点击第一个div的第二个按钮时显示回复。

PHP代码:

<?php if(!isset($_SESSION['fname']) && !isset($_SESSION['username']) &&   !isset($_SESSION['email'])) { 
    echo "<h1>You must be logged in to comment</h1>"; 
} else { ?> 
<div id="comment"> 
<form action="createcomment.php?videoid=<?php echo $_GET['id']; ?>" method="post"> 
    Comment: <br /><textarea name="comment" placeholder="Your comment..."></textarea><br /> 
    <input type="submit" name="submit" value="Post Comment" class="btn btn-warning"> 
</form> 
</div> 
<?php } ?> 
<div id="comments"> 
<?php  $sql = "SELECT * FROM comments WHERE videoid = " . $_GET['id']; 
$result = mysqli_query($db, $sql); 
while($row = mysqli_fetch_assoc($result)) { 
if(!empty($result)) { 
?> 
<div class="comment"> 
<h5><?php echo $row['name']; ?></h5> 
<p><?php echo $row['comment']; ?></p> 
<button class="btn btn-primary btn-small">Reply</button> 
<div id="reply"> 
<form action="replycomment.php?videoid=<?php echo $_GET['id']; ?>&commentid=<?php echo $row['id']; ?>" method="post"> 
    Reply Message: <br /><textarea name="comment" placeholder="Your comment..."></textarea><br /> 
    <input type="submit" name="submit" value="Post Reply" class="btn btn-warning"> 
</form> 
</div> 
</div> 
<?php }else { 
    echo "<h1>There are no comments.</h1>"; 
} 
}?> 
</div> 

jQuery代码:

<script> 
$(document).ready(function(){ 
     $("#reply").hide(); 
$("#comments > div > button").click(function(){ 
    $("#reply").slideToggle(); 
}); 
}); 
</script> 

jQuery的应该是隐藏所有回复的div的,当你点击回复格打开,而不是第一个按钮的作品,但最后一个按钮打开第一个,我不知道发生了什么。

谢谢。

+5

ID应该是整个文档 – santosh

+0

什么是错误您获得独特? – santosh

+0

我没有得到一个错误@santosh – madforep

回答

1

整个DOM中只能有一个ID。您有一个ID为“回复”的元素。由于数据库循环了所有的注释,因此会有多个元素的ID为“reply”。 此语法不正确。

现在,如果你点击一个按钮来切换ID为“reply”的元素,它们都会切换。这不是你想要的。将HTML更改为:

<button class="btn btn-primary btn-small">Reply</button> 
<div class="reply"> 
    <form action="replycomment.php?videoid=<?php echo $_GET['id']; ?>&commentid=<?php echo $row['id']; ?>" method="post"> 
    Reply Message: <br /><textarea name="comment" placeholder="Your comment..."></textarea><br /> 
    <input type="submit" name="submit" value="Post Reply" class="btn btn-warning"> 
    </form> 
</div> 

请注意,我删除了id,并添加了该类。 DOM中可以有多个类。因此,jQuery的需要隐藏的所有类的,所以:

$(document).ready(function(){ 
    $(".reply").hide(); 
    // Hides all the elements with class="reply" 
}); 

现在我们需要的是按一下按钮的动作。如果我们只是将标签更改为点并将其设为类,它仍然会将所有元素与答复类切换。我们只需要切换点击按钮后面的元素...对吧?

所以:

$(document).ready(function(){ 
    $("#comments > div > button").click(function(){ 
    $(this).nextAll('.reply:first').slideToggle(); 
    // Gets all the next sibling elements under the same parent, and selects the first one with the class="reply" 
    }); 
}); 
+0

谢谢你的作品 – madforep

相关问题