【问题标题】:Jquery works only on first forloop element?Jquery 仅适用于第一个 forloop 元素?
【发布时间】:2011-08-25 19:26:33
【问题描述】:

这是我的 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代码在这里:

<script>
    $(function() {


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

    });
</script>

但这里只有第一个 div 在 for 循环内切换。 Jquery 不适用于剩余的 for 循环元素。你能给我正确的jQuery代码吗?谢谢。

【问题讨论】:

  • 任何给定的 id 都不应该有多个元素。 ID 应该是唯一的;重复它们只是自找麻烦。
  • 我已经更改了 ID,但我的概率相同。帮助。

标签: jquery python django jquery-selectors django-templates


【解决方案1】:

进行此更改:

<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

【讨论】:

    【解决方案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>
    

    【讨论】:

    • 现在无论按下哪个元素按钮,所有的 forloop 元素都会被切换。
    • +1 这比我的好:不需要.each()(我用过的),更具体的next()选择器,此外,它已经在我还在写我的时候发布了。 @Nazim:请随时重新接受更好的解决方案(我鼓励你这样做)。
    猜你喜欢
    • 2013-01-11
    • 2012-06-12
    • 1970-01-01
    • 2012-06-22
    • 2015-11-03
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    相关资源
    最近更新 更多