2011-05-15 67 views
0

这里是我的Django的模板:jquery只适用于第一个forloop元素?

{% for feed in feeds %} 
    <div id="feed"><b>At {{feed.location}}:<b> {{feed.msg}}</b></div></br> 
    <button id="bb{{feed.id}}">Add Comment</button> 
    <div id="commentbox" style="display:none;"> 
     <form method="post" action="/comment/{{feed.id}}/"> 
     {{cform.as_p}} 
     <input type="submit" value="comment" /> 
     </form> 
    </div> 

{% endfor %} 

jQuery代码是在这里:

<script> 
    $(function() { 


      $("#bb.").click(function() { 
      $("#commentbox").toggle("slow"); 
      }); 

    }); 
</script> 

但这里只有第一个div切换里面的for循环。 Jquery不适用于剩余的循环元素。你可以请给我适当的jQuery代码。谢谢。

+3

你永远不应该有任何给定的ID多个元素。 Ids应该是独一无二的;重复他们只是要求麻烦。 – 2011-05-15 07:17:29

+0

我已经更改了ID,但我的概率相同。帮帮我。 – 2011-05-15 07:25:37

回答

3

进行此更改:

<button class="bb" id="bb{{feed.id}}">Add Comment</button> 
<div class="commentbox" style="display:none;"> 

这一个:

$(document).ready(function() { 
    $(".bb").each(function(){ 
    $(this).click(function() { 
     $(this).next().toggle("slow"); 
    }); 
    }); 
}); 

更新: 这里是a working demo

+0

非常感谢... :) – 2011-05-15 07:47:24

+0

不客气;) – 2011-05-15 07:51:38

2

正如Tikhon所建议的,使用重复的ID是在寻求麻烦。为这些元素添加一个类并使用基于该类的jQuery选择器,你应该没问题。喜欢的东西,

{% for feed in feeds %} 
<div id="feed"><b>At {{feed.location}}:<b> {{feed.msg}}</b></div></br> 
<button class="bb" id="bb{{feed.id}}">Add Comment</button> 
<div class="commentbox" style="display:none;"> 
    <form method="post" action="/comment/{{feed.id}}/"> 
    {{cform.as_p}} 
    <input type="submit" value="comment" /> 
    </form> 
</div> 
{% endfor %} 

<script> 
$(function() { 
     $(".bb").click(function() { 
      $(this).next('.commentbox').toggle("slow"); 
     }); 
}); 
</script> 
+0

现在无论按下哪个元素按钮,都可以切换所有forloop元素。 – 2011-05-15 07:41:35

+0

谢谢,得到它的工作。 – 2011-05-15 07:47:50

+0

+1这比我的更好:不需要'.each()'(我使用过)和更具体的'next()'选择器,除此之外,在我还在写我的时候已经发布了。 @Nazim:请随时重新接受更好的解决方案(我鼓励你)。 – 2011-05-15 07:56:31