2017-04-05 5 views
0

私のウェブページにはコメントシステムを行っています。 ウェブサイト誰もがコメントすることができ、データベースからの要素のグループを示していますjqueryで開閉するdivs

要素1($ element_id = 1) - >のコメントを読む...

エレメント2($ element_id = 2) - > ...

エレメント3をコメントを読む($ element_id = 3) - > ...コメントを読む

誰かが一つの要素のコメントを読みたい場合は、 "コメントを読む..." をクリックすることができ、新しい部門が開かれます:

<div class="comments_more" id="comments_more"> Read comments... 
<div class="comments_div" id="comments_div" > 
<?php include/comments.php ?> 
<?php echo $element_id; ?> 
</div> </div> 

のdivを開くためにjqueryのコードは、すべての要素のために完璧に動作します:

$(document).ready(function(){ 
    $('.comments_more').click(function() { 
    $(this).find('#comments_div').show('slide'); 
    }); 
    }) 

、私はそれの外のdivたときにユーザーがクリックを閉じるには素敵なjqueryのを見つけました:

$(document).mouseup(function (e){ 
var container = $("#comments_div"); 
if (!container.is(e.target) // if the target of the click isn't the container... 
    && container.has(e.target).length === 0) // ... nor a descendant of the container 
{  container.hide(); } 
}); 

問題は、それがは、最初のの「コメントの読み込み...」(最初の要素)に対してのみ機能します。

+0

:このような何かを試してみてください複数の異なるHTML要素が異なる要素の場合、同じIDを持つことはできますか?](http://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same- id-if-theyre-different-eleme) – Ionut

答えて

2

あなたが1つのページに複数のIDを持つことができない、のような代わりセレクタとしてクラスを使用してみてください:私は繰り返しHTMLがどのように見えるかでここに推測している

$(".comments_div") 
0

が、

$(document).ready(function() { 
 
    $('.comments_more').click(function() { 
 
    $(this).find('.comments_div').show('slide'); 
 
    }); 
 
}) 
 

 
$(document).mouseup(function(e) { 
 
    var container = $(".comments_div"); 
 
    if (!container.is(e.target) && container.has(e.target).length === 0) 
 
    { 
 
    container.hide(); 
 
    } 
 
});
.comments_div { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div class="comments_more"> Read comments... 
 
    <div class="comments_div"> 
 
    Comments 1 
 
    </div> 
 
</div> 
 
<div class="comments_more"> Read comments... 
 
    <div class="comments_div"> 
 
    Comments 2 
 
    </div> 
 
</div> 
 
<div class="comments_more"> Read comments... 
 
    <div class="comments_div"> 
 
    Comments 3 
 
    </div> 
 
</div>

関連する問題