2011-05-15 69 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