首页 > 解决方案 > 单击动态按钮后未显示信息(使用切换)

问题描述

单击“更多信息”按钮后,我试图显示一些附加信息。

首先,div 是根据我的数据库动态生成的。哪个 div 包含一个“更多信息”按钮,单击该按钮应显示更多信息。但是,只有第一个按钮有效,单击时会显示所有生成的 div 中的所有“更多信息”。

我只想显示/隐藏与我单击的 div 相关的更多信息,而其他信息仍然隐藏。

这是 HTML/PHP

<div id="event_info">
   <img src= "<?php echo $row['img'];?> "/>
   <div class="event_description">
      <h1><?php echo $row['gathering_name'];?></h1>
      <b>Hosted By:</b> <?php echo $row['event_host'];?> </br>
      <b>Location:</b> <?php echo $row['city'].', '. $row['state']; ?></br>
      <b>Date:</b> <?php $event_date = strtotime($row['event_start']);
         echo date("F jS, Y" , $event_date);?></br></br>
      <!-- MORE INFO ABOUT THE GATHERINGS -->
      <button class="findButton2" id="<?php echo $row['id'];?>">MORE INFO</button>
      <div id="<?php echo $row['id'];?>" class="event_moreinfo">
         <?php echo $row['description'];?></br>
         <b>Gym Name: </b> <?php echo $row['gym_name'];?> </br>
         <b>Gym Address: </b>  <?php echo $row['street_address'];?></br>
         <?php echo $row['city'].', '.$row['state'].', '. $row['country'];?></br>
         <b>Nearest Airport: </b> <?php echo $row['nearest_airport'];?></br>
         <b>Expected Attendance: </b> <?php echo $row['attendance']; ?></br>
         <b>Average Ticket Cost: </b> <?php echo $row['event_cost']; ?> </br>
         <b>Contact: </b> <a href = "mailto:<?php echo $row['host_email'];?>"> Host Email</a>               
      </div>
   </div>
</div>

这是我的脚本(jQuery)

$(document).ready(function() {
    var event_id = $(".findButton2").attr("id");
    $('#' + event_id).on('click', function() {
        $(".event_moreinfo").toggle(1000);
    });
});

标签: javascriptphpjqueryhtml

解决方案


发生这种情况是因为所有动态 div 具有相同的类名event_moreinfothis与你喜欢的下面next一起使用。它只会在单击按钮时切换下一个具有类的 div 。toogledivevent_moreinfo

$(document).ready(function() {
    var event_id = $(".findButton2").attr("id");
    $('#' + event_id).on('click', function() {
        $(this).next(".event_moreinfo").toggle(1000);
    });
});

推荐阅读