简体   繁体   English

jQuery仅在第一个forloop元素上起作用?

[英]Jquery works only on first forloop element?

Here is my Django template: 这是我的Django模板:

{% 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 code is here: jQuery代码在这里:

<script>
    $(function() {


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

    });
</script>

But here only the first div toggles inside the for loop. 但是这里只有第一个div在for循环内切换。 Jquery does not work for the remaining for loop elements. jQuery对于其余的for循环元素无效。 Can you please give me the proper jQuery code. 您能给我合适的jQuery代码吗? Thanks. 谢谢。

make this change: 进行更改:

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

and this one: 还有这个:

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

Update: And here is a working demo . 更新:这是一个有效的演示

As Tikhon suggests, using duplicate ID's is asking for trouble. 正如Tikhon所建议的那样,使用重复ID会带来麻烦。 Add a class to these elements and use a jQuery selector based on the class and you should be fine. 向这些元素添加一个类,并使用基于该类的jQuery选择器,您应该会很好。 Something like, 就像是,

{% 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 %}

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM