2017-04-12 42 views
0

我正在做一個評論系統。昨天我在stackoverflow中詢問同樣的問題,我沒有得到任何答案。現在我簡化了代碼,所以我希望它更易於理解。如果有人嘗試過,我還會編寫完整的代碼。執行JavaScript,進入之前用jQuery/JavaScript打開的div

主HTML頁面有多個div

<html> 
<head> 
<link rel="stylesheet" type="text/css" href="style.css"> 
<script src="http://code.jquery.com/jquery-3.0.0.min.js"></script> 
<script type="text/javascript" src="jscripts/actions.js"></script> 
</head> 

<body> 
<div class="comments_div" id="comments_div" data-id="22" > 
    div_22---> 
<div class="comments_more_22" id="comments_more"> </div> 
</div> 
<br> 
<div class="comments_div" id="comments_div" data-id="23" > 
    div_23---> 
<div class="comments_more_23" id="comments_more"> </div> 
</div> 
<br> 
<div class="comments_div" id="comments_div" data-id="24" > 
    div_24---> 
<div class="comments_more_24" id="comments_more"> </div> 
</div> 
<br> 
</body> 

的jQuery/JavaScript函數打開/隱藏 div和顯示POST_ID(數據ID)。它的作品非常完美!

//Open div 
$(function() { 
    $(".comments_div").click(function() { 
    var post_id = $(this).attr('data-id');  
    $.ajax({ 
     url: "jscripts/comment.php", 
     type: "POST", 
     data: { post_id: post_id }, 
     success: function(datos) { 
     $('.comments_more_' + post_id).html(datos); 
     $('.comments_more_' + post_id).show('slow'); 
     //alert(post_id); 
     } 
    }); 
    }); 
}) 


//Hide div 
$(document).mouseup(function (e){ 
    var container = $('div[id^="comments_more"]'); 
    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('slow'); } 
}); 

//Put text in some div 
function showText() 
{ document.getElementById("flash").textContent = 'works!';} 

...和comment.php(這裏的代碼會更加複雜,形式,驗證碼等)

<?php 
    echo 'post_id: '; 
    echo $_POST['post_id']; 
?> 

<div class="flash" id="flash">- </div> 

<span style="margin-left:20px;"><small>click<a href='javascript: showText();'>here</a> </small></span><br/> 

尼斯,是不是? 但是我需要執行另一個JavaScript:showText()。當您按以下順序點擊該腳本時,該腳本將起作用:div_24,div_23,div_22。但停止工作,當你嘗試點擊第一div_22,然後div_23,...等

+0

一是多種元素的所有ID不能相同 –

+0

謝謝,這是真的,但它並沒有解決問題。 – Kalimero

回答

0

嗯,我解決了這個問題:div「閃光燈」必須有一個唯一的ID,所以showText可以找到正確的div。

<?php 
    echo 'post_id: '; 
    echo $_POST['post_id']; 
$post_id=$_POST['post_id']; 
?> 

<div class="flash" id="flash_<?php echo $post_id; ?>">- </div> 

<span style="margin-left:20px;"><small>click<a href='javascript: showText();'>here</a> </small></span><br/> 


<script type="text/javascript"> 
//Put text in some div 
function showText() 
{ 
var post_id = "<?php echo $post_id; ?>" ; 
document.getElementById("flash_" + post_id).textContent = 'works!'; 
} 

</script> 

:P

相關問題