2013-03-22 90 views
5

我正在编写自己的轻量级博客平台(我试图学习PHP & jQuery,所以我不只是想使用Wordpress)。使用PHP,我有一个分页系统,每页显示5篇博文。在我的while循环中,我想要有一个链接,指出“发表评论”,点击后,将打开一个包含文本框以输入评论的DIV。我正在使用的当前代码打开页面上的所有5个评论DIV。我需要能够给每个这些commif DIV提供一个唯一的ID(基于我假设的博客文章ID),并将其放入我的jquery切换函数中,以便在单击链接时只打开一个注释DIV,而不是全部他们。谁能帮帮我吗?切换动态创建的div

这里是我的jQuery该页面中打开了所有切换的div:

<script type="text/javascript"> 
    $(document).ready(function() { 
    $(".toggleCommentBox").click(function() { 
     $(".commentBox").toggle() 
    }); 
    });  
</script> 

下面是我在while循环的代码显示的博客文章和链接:

<a href = "#" class = "toggleCommentBox">Leave a Comment</a> 

<div class = "commentBox" style = "display:none;"> 
    ...Form stuff in here 
</div> 

我不不需要关于commentBox div中表单内容的帮助,我只需要帮助jQuery使每个页面上的5个评论框独一无二,并且它们都可以单独切换,而不是一个链接打开所有5个切换就像现在发生的一样,页面上的DIV。任何人可以给我的帮助将不胜感激。

回答

2

使用jQuery下一个功能:

<script type="text/javascript"> 
    $(document).ready(function() { 
    $(".toggleCommentBox").click(function() { 
     $(this).next(".commentBox").toggle() 
    }); 
    });  
</script> 

http://api.jquery.com/next/

+1

谢谢,这个作品完美! – 2013-03-22 06:24:15

+0

好工作。如何添加像fontawesome开放/关闭图标? – Perspolis 2015-07-10 20:36:29

4

尝试是这样的

<script type="text/javascript"> 
$(document).ready(function() { 
$(".toggleCommentBox").each(function{ 

    var getId = $(this).attr('getId'); 
    $(this).click(function(){ 

     $("#commentBox"+getId).toggle(); 
    }) 
    }) 
});  

<a href = "#" class = "toggleCommentBox" getId='1' >Leave a Comment</a> 

<div class = "commentBox" style = "display:none;" id="commentBox1"> 
...Form stuff in here 
</div> 

希望你明白我想牛逼o说

+0

谢谢!我使用Baserati的答案,因为它更简单一些。谢谢你:) – 2013-03-22 06:26:23