2017-03-07 27 views
0

我正在爲客戶端創建網站,但我主要是前端開發人員。我不得不建立一個while循環(這工作得很好)來建立一個畫廊。客戶希望在畫廊上顯示前/後。我選擇使用TwentyTwo jQuery插件。但是,我有一個問題。它只顯示第一個容器,顯示得很好。在PHP while循環中使用jQuery函數

必要的jQuery,inline和css文件顯示在上面鏈接的頁面上。我使用bootstrap作爲框架。這裏是我的代碼:

$(window).load(function() { 
 
    $("#container1").twentytwenty(); 
 
});
<div class="row"> 
 
    <div class="col-lg-12"> 
 
    <h2><span class="color">Our Gallery</span> </h2> 
 
    <?php 
 
      //Selects all images 
 
      $sql = $GLOBALS['gmysqli']->query("SELECT image FROM gallery ORDER BY postDate DESC") or die($GLOBALS['gmysqli']->error); 
 
    
 
      while ($row = $sql->fetch_assoc()) { 
 
       $image = $row["image"]; 
 
       ?> 
 
     <div class="col-lg-3 col-md-4 col-xs-6 thumb"> 
 
     <div id="container1" class="twentytwenty-container"> 
 
      <img src="<?php echo $beforeimage; ?>"> 
 
      <img src="<?php echo $afterimage; ?>"> 
 
     </div> 
 
     </div> 
 
     <?php } ?> 
 
    </div> 
 
</div>

+0

,這將導致你的文檔中重複的ID。這是無效的。 除此之外:你如何調用jQuery函數?現在,問題與jQuery本身無關,只與PHP和Mysql有關。 '$ row'是否包含您期望它執行的所有圖像? – empiric

+0

是的,它會顯示所有圖像,如果我沒有這個jQuery功能的結構。我使用該頁面上包含的腳本調用jQuery函數。它是 有沒有什麼方法可以讓容器ID每次都有所不同?在他們包含的示例頁面中,他們使用與該圖像相同的每個div的ID。 – Cody

回答

0

這裏的問題是您在php循環中生成的重複ID。這會導致無效的HTML,並將其用作選擇器時可能會導致問題。

您可以切換到使用類選擇:

$(document).ready(function(){ 
    $(".twentytwenty-container").twentytwenty(); 
}); 

我更新了ready處理程序的建議結構。或簡寫:

$(function() { 
    $(".twentytwenty-container").twentytwenty(); 
}); 

當如果你想堅持的ID,你可以一個迭代變量添加到您的循環和使用attribute使用類選擇,你可以在HTML元素 擺脫ID的選擇:

$(function() { 
 
    $("div[id^='container-']").twentytwenty(); 
 
});
<?php 
 
$i = 0; 
 
while($row = $sql->fetch_assoc()) { 
 
    $image = $row["image"]; ?> 
 
    <div class="col-lg-3 col-md-4 col-xs-6 thumb"> 
 
    <div id="container-<?php echo $i; ?>" class="twentytwenty-container"> 
 
     <img src="<?php echo $beforeimage; ?>"> 
 
     <img src="<?php echo $afterimage; ?>"> 
 
    </div> 
 
    </div> 
 
<?php 
 
    $i++; 
 
} ?>

您使用的是循環中的固定ID
0

嘗試沒有爲了通過聲明。

例子:

<div class="row"> 
       <div class="col-lg-12"> 
        <h2><span class="color">Our Gallery</span> </h2> 
        <?php 
          //Selects all images 
          $sql = $GLOBALS['gmysqli']->query("SELECT image FROM gallery") or die($GLOBALS['gmysqli']->error); 

          while($row = $sql->fetch_assoc()) 
          { $image = $row["image"]; ?>       
           <div class="col-lg-3 col-md-4 col-xs-6 thumb"> 
           <div id="container1" class="twentytwenty-container"> 
           <img src="<?php echo $beforeimage; ?>"> 
           <img src="<?php echo $afterimage; ?>"> 
           </div> 
           </div> 
          <?php } ?> 
          </div> 
         </div> 

如果你可以分享你的數據庫是如何填寫能夠更容易幫助你。

和項目鏈接。

無論如何,我希望能幫到你。