2013-03-22 87 views
5

我正在編寫自己的輕量級博客平臺(我試圖學習PHP & jQuery,所以我不只是想使用Wordpress)。使用PHP,我有一個分頁系統,每頁顯示5篇博文。在我的while循環中,我想要有一個鏈接,指出「發表評論」,點擊後,將打開一個包含文本框以輸入評論的DIV。我正在使用的當前代碼打開頁面上的所有5個評論DIV。我需要能夠給每個這些commif DIV提供一個唯一的ID(基於我假設的博客文章ID),並將其放入我的jquery切換函數中,以便在單擊鏈接時只打開一個註釋DIV,而不是全部他們。誰能幫幫我嗎?切換動態創建的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> 

我不不需要關於commentBox div中表單內容的幫助,我只需要幫助jQuery使每個頁面上的5個評論框獨一無二,並且它們都可以單獨切換,而不是一個鏈接打開所有5個切換就像現在發生的一樣,頁面上的DIV。任何人可以給我的幫助將不勝感激。

回答

2

使用jQuery下一個功能:

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

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

+1

謝謝,這個作品完美! – 2013-03-22 06:24:15

+0

好工作。如何添加像fontawesome開放/關閉圖標? – Perspolis 2015-07-10 20:36:29

4

嘗試是這樣的

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

希望你明白我想牛逼o說

+0

謝謝!我使用Baserati的答案,因爲它更簡單一些。謝謝你:) – 2013-03-22 06:26:23