【问题标题】:Toggle dynamically created divs切换动态创建的 div
【发布时间】:2013-03-22 05:43:11
【问题描述】:

我正在编写自己的轻量级博客平台(我正在尝试学习 PHP 和 jQuery,所以我不只是想使用 Wordpress)。使用 PHP,我有一个分页系统,每页显示 5 篇博客文章。在我的 while 循环中,我想要一个显示“发表评论”的链接,单击该链接将打开一个 DIV,该 DIV 有一个文本框来输入评论。我正在使用的当前代码在页面上打开了所有 5 个评论 DIV。我需要能够为每个评论 DIV 提供一个唯一 ID(基于我假设的博客文章的 ID)并将其放在我的 jquery 切换功能中,以便在单击链接时只打开一个评论 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>

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

【问题讨论】:

  • 清晰地描述(正是我遇到的问题);做得很好。

标签: jquery html toggle


【解决方案1】:

试试这样的

<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>

希望你明白我想说什么

【讨论】:

  • 谢谢!我正在使用Baserati的答案,因为它更简单一些。不过还是谢谢你:)
  • 第 3 行缺少封闭的括号;它应该是$(".toggleCommentBox").each(function(){
  • 这个解决方案对我有用(而@basarat 提供的解决方案没有;但我不知道为什么)。
【解决方案2】:

使用jquery下一个函数:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多