2017-04-05 109 views
0

我正在爲我的網頁做一個評論系統。 該網站顯示的一組從數據庫元素,每個人都可以發表評論:用jquery打開和關閉div

元1($ element_id = 1) - >閱讀評論...

元2($ element_id = 2) - >閱讀評論...

元3($ element_id = 3) - >閱讀評論...

當有人想讀一個元素的註釋,可以在 「閱讀評論...」 咔嚓並打開一個新的div:

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

jQuery代碼打開DIV的每一個元素完美的作品:

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

現在,我找到了一個不錯的jQuery當用戶點擊它以外關閉的div:

$(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-更有耐力,不同-eleme) – Ionut

回答

2

你不能有一個頁面上的多個ID,請嘗試使用類作爲選擇而不是像:

$(".comments_div") 
0

我猜在這裏重複的HTML是什麼樣子,但嘗試是這樣的:

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