2017-04-12 13 views
0

私はコメントシステムを行っています。昨日私はstackoverflowで同じ問題を尋ねましたが、私は答えを得られませんでした。今ではコードを単純化していますので、わかりやすくしてください。私はまた、誰かがそれを試してみたら完全なコードを書いています。jQuery/JavaScriptで以前に開いたdivにJavaScriptを実行します。

メイン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(ここでのコードは、フォーム、CAPTCHAのと、より複雑になる、など)

<?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 "flash"は一意の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

関連する問題