在循环php jquery中隐藏和显示内容

时间:2015-10-20 05:07:53

标签: php jquery html pdo

大家好我需要一些帮助我有这些代码我需要通过id显示内容 在clik显示内容后,我需要以相同的ID显示内容

    <script type="text/javascript">
    function toggleAndChangeText() {
         $('#divToToggle').toggle();
         if ($('#divToToggle').css('display') == 'none') {
              $('#aTag').html('Collapsed text mode &#9658');
         }
         else {
              $('#aTag').html('Expanded text mode &#9660');
         }
    }
 </script>

 <style>
 #divToToggle{display:none;}
 </style>

和这段代码php / html

          <?php 
        $stmt = $DB_con->prepare("SELECT * FROM `topic` ORDER BY id");
        $stmt->execute();   
        foreach ($stmt->fetchAll() as $row) {
        echo" 
        <div class='Post'>
        <div class='rgt Pimg'><a href='post.php?id=".$row['id']."'><img src='".$row['e_title']."' class='Pimg'/></a></div>
        <div>
        <a id='aTag' href='javascript:toggleAndChangeText()'>
           Show Content
        </a>
        <div id='divToToggle'>".$row['e_content']."</div>
        </div>
        ";
        }
      ?>

1 个答案:

答案 0 :(得分:1)

您不能对多个元素使用相同的ID。请改用class

将您的脚本更改为:

   $(document).ready(function(){
    $("a.aTag").on("click", function(){
       var toggleElement = $(this).closest("div").find(".divToToggle");
       toggleElement.toggle();
         if (toggleElement.css('display') == 'none') {
              $(this).html('Collapsed text mode &#9658');
         }
         else {
              $(this).html('Expanded text mode &#9660');
         }
    }); 

 }); 

你的PHP代码:

 <?php 
    $stmt = $DB_con->prepare("SELECT * FROM `topic` ORDER BY id");
    $stmt->execute();   
    foreach ($stmt->fetchAll() as $row) {
    echo" 
    <div class='Post'>
    <div class='rgt Pimg'><a href='post.php?id=".$row['id']."'><img src='".$row['e_title']."' class='Pimg'/></a></div>
    <div>
    <a class='aTag' href='javascript:toggleAndChangeText()'> 
       Show Content
    </a>
    <div class='divToToggle'>".$row['e_content']."</div>
    </div>
    ";
    }
  ?>