【问题标题】:Get specific div when clicking button in php while loop在php while循环中单击按钮时获取特定的div
【发布时间】:2019-03-14 14:33:56
【问题描述】:

我有一个 while 循环吐出多个帖子,每个帖子都有一个名为“flag_btn”的 div 按钮,单击时我试图显示我的表单的相应 div 容器,所有这些都从 PHP while 循环中显示 -

    $sql = "SELECT * FROM table";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
          $post_id = $row['post_id'];
echo "
<div id='flag_btn'>flag </div>
<div id='flag_cont' style='display:none'>
    <form method='post' class='flag_form'>
        <input type='radio' name='flag_reason' value='off'>Its Offensive<br>
        <input type='submit' value='Submit'>
    </form>
</div>
";

这里是jquery点击事件——

$('#flag_btn').click(function() {
    $(this).closest('#flag_cont').show(200);
});

但它不起作用..如何让点击事件仅显示与被点击的帖子相对应的 flag_cont?

*注意:我没有发布 php while 循环,因为我觉得这是不必要的..

【问题讨论】:

  • 一个页面上是否有多个具有相同 ID 的标志按钮? ID 应该是唯一的,每页只有一个。尝试将其更改为一个类:$('.flag_btn').click(function() { $(this).find('.flag_cont').show(200); });
  • 您绝对应该在问题中包含 php 循环。
  • 好的,刚刚添加了while循环
  • @RyanD 在这种情况下,知道循环的结构可以让其他人形成适合您问题的答案,因为您很可能需要元素上的唯一 ID:s 或其他不使用 ID:s 的解决方案。

标签: javascript php jquery while-loop onclick


【解决方案1】:

我认为next() 在这种情况下更好。

我还将“按钮”上的id 替换为class,因此它适用于多个“按钮”。

$('.flag_btn').click(function() {
  $(this).next('#flag_cont').show(200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='flag_btn'>flag1</div>
<div id='flag_cont' style='display:none'>
  <form method='post' class='flag_form'>
    <input type='radio' name='flag_reason' value='off'>Its Offensive1<br>
    <input type='submit' value='Submit'>
  </form>
</div>
<div class='flag_btn'>flag2 </div>
<div id='flag_cont' style='display:none'>
  <form method='post' class='flag_form'>
    <input type='radio' name='flag_reason' value='off'>Its Offensive2<br>
    <input type='submit' value='Submit'>
  </form>
</div>
<div class='flag_btn'>flag3 </div>
<div id='flag_cont' style='display:none'>
  <form method='post' class='flag_form'>
    <input type='radio' name='flag_reason' value='off'>Its Offensive3<br>
    <input type='submit' value='Submit'>
  </form>
</div>

【讨论】:

  • 是的,那是我的问题,我忘记将按钮设为一个类..并使用下一个而不是最接近的..谢谢队友的欢呼!
猜你喜欢
  • 2019-07-01
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多