简体   繁体   English

JQuery单击slidetoggle仅适用于PHP重复DIVS的第一个DIV

[英]JQuery click slidetoggle only working for the first DIV of PHP repeated DIVS

I have DIVs which are repeated for records in a database via PHP, and I have jquery script which on click should expand a div bellow out. 我有DIV通过PHP重复数据库中的记录,我有jquery脚本,点击后应该展开一个div。

This is the simple code for the slide, generic stuff: 这是幻灯片的简单代码,通用的东西:

<script src =
  "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script> 
  $(document).ready(function(){        // Line A   
    $("#flip").click(function(){       // Line B
      $("#panel").slideToggle("slow"); // Line C
    });
  });
</script>


<body>

  <div style="background:red" id="flip">Click to slide the panel down or up</div>

  <div style="background:green" id="panel">Oh Hello There</div>


#panel {
    display:none;
    }

Fiddle: http://jsfiddle.net/hpvgp/3/ 小提琴: http//jsfiddle.net/hpvgp/3/

However when I try and apply this to my code where I have the divs looped out, it only works for the first div. 但是,当我尝试将此应用于我的代码时,我将div循环出来,它只适用于第一个div。

Current code: 当前代码:

<?php
$webserver = 'localhost'; 
$administrator = 'root';
$password = '';
$db_name = 'cdb';
$db = mysqli_connect($webserver, $administrator, $password, $db_name)
  or die('Error connecting');

if( isset($_REQUEST['page'])) {
  $_SESSION['page'] = $_REQUEST['page'];
}else{
  $_SESSION['page'] = 1;
}
$records_per_page = 8;
$query = "SELECT * FROM cars";
$result = mysqli_query($db, $query)
  or die("Error in query: '$query'");
$row = mysqli_fetch_assoc($result);
$i = 0;
$start = ($_SESSION['page'] - 1) * $records_per_page;
$end = ($_SESSION['page']) * $records_per_page;
while($row = mysqli_fetch_assoc($result) and $i < $end) {
  $i++;
  if( $i > $start ) 
  {;
    echo'
    <div><br><br>

      <div id="flip" class="navbar navbar-inverse" style ="margin-top:-40px; height:128px"> 

          <div style="float:left; height:100px; width:200px">
            <img src="'.$row['logo'].'" style="margin:10px; float:left" height="100"/></div> 
            <div style="float:left"><h2>'.$row['make'].' '.$row['model'].'</h2></div>
      </div>

    </div>

    <div><img id="panel" style="padding-bottom: 100px" src="images/cars/'.$row['carIndex'].'.jpg" height="300"/><div> ';
  }
}

I'm currently using Bootstrap, not sure if that would matter. 我目前正在使用Bootstrap,不确定这是否重要。

I find it really strange that this would work for the first DIV but not any of the following ones. 我发现这对于第一个DIV而不是以下任何一个DIV都很有用。 Do I perhaps need to place the script somewhere else? 我是否需要将脚本放在其他地方? I'm really lost on this. 我真的迷失了。

Any help appreciated -Tom 任何帮助表示赞赏-Tom

IDs are expected to be unique. ID应该是唯一的。 Never use the same id more than once in a document. 切勿在文档中多次使用相同的ID。 Change your code to: 将您的代码更改为:

while($row = mysqli_fetch_assoc($result) and $i < $end) {
    $i++;
    if( $i > $start ) 
    {
        echo'
          <div><br><br>

               <div class="flip navbar navbar-inverse" data-panel="panel_' + $i . '" style ="margin-top:-40px; height:128px"> 

                <div style="float:left; height:100px; width:200px">
                    <img src="'.$row['logo'].'" style="margin:10px; float:left" height="100"/></div> 
                <div style="float:left"><h2>'.$row['make'].' '.$row['model'].'</h2></div>
               </div>
         </div>

         <div><img id="panel_' . $i . '" style="padding-bottom: 100px" src="images/cars/'.$row['carIndex'].'.jpg" height="300"/><div> ';
    }
}

And now chang your javascript to: 现在将你的javascript改为:

<script> 
  $(document).ready(function(){          
    $(".flip").click(function(){  
      var panelId = $(this).attr('data-panel');   
      $('#' + panelId).slideToggle("slow")
    });
  });
</script>

This way your IDs are unique, and each panel is related to its 'flip' div via a custom attribute ( data-panel ) that contains the panel's ID. 这样,您的ID就是唯一的,每个面板都通过包含面板ID的自定义属性( data-panel )与其“翻转”div相关联。

You're assigning the same ID to multiple divs. 您正在为多个div分配相同的ID。 An ID is, by definition, unique. 根据定义,ID是唯一的。 If you set the same ID on more than one element then your HTML will be invalid and all bets are off. 如果您在多个元素上设置相同的ID,则您的HTML将无效并且所有投注均已关闭。 jQuery will use GetElementByID () to select which element to grab when you pass it an ID, and the behaviour of GetElementByID when there's more than one element with the same ID is undefined. jQuery将使用GetElementByID()来选择在向其传递ID时要抓取的元素,并且当多个具有相同ID的元素未定义时,GetElementByID的行为。 It could in theory do anything (throw an exception, return the first matching element, select the last matching element, select a single matching element at random, make demons fly out of your nose, etc). 它理论上可以做任何事情(抛出异常,返回第一个匹配元素,选择最后一个匹配元素,随机选择一个匹配元素,让恶魔飞出你的鼻子等)。

As you want your code to affect more than one element, then all those elements have something in common. 由于您希望代码影响多个元素,因此所有这些元素都有一些共同点。 Therefore they all belong to the same class of elements, and you should use class="someclass" to indicate which elements belong to that class. 因此它们都属于同一类元素,您应该使用class =“someclass”来指示哪些元素属于该类。 HTML like: HTML喜欢:

<div class="flip navbar navbar-inverse" style ="margin-top:-40px; height:128px">

JS like: JS喜欢:

$(".flip").click(function(){       // Line B

As an advice that works at least for me, when I'm using classes for bind functions, I like to difference that class to the others, so I add the prefix "js-" to the class. 作为一个至少对我来说有用的建议,当我使用类来实现绑定函数时,我喜欢将该类与其他类相区别,所以我将前缀“js-”添加到类中。 That way I'll know that it's not a design class, that an event is bind to that class and that class should not be removed. 这样我就知道它不是一个设计类,一个事件绑定到该类,并且该类不应该被删除。 So I'll use "js-flip" instead "flip". 所以我会用“js-flip”代替“翻转”。 But it is just and advice as good practises and some people cannot be agree with me, but it has been quite useful in projects where more than one person were touching the same code. 但它只是和建议作为良好实践,有些人不能同意我,但它在多个人触及相同代码的项目中非常有用。 Also I will not add css styles to that class because the porpoise of it is only programmatic, so it will be transparent for the designers. 此外,我不会为该类添加css样式,因为它的海豚只是程序化的,所以它对设计师来说是透明的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM