2012-02-05 41 views
0

我需要在獲取Div的寬度並根據元素的數量限制mySQL查詢?

<li><img class='1'><img class='1'><img class='1'></li> 
<li><img class='1'><img class='1'><img class='1'></li> 

以顯示圖像的數量,但作爲我的div是自動根據屏幕寬度增加。我需要根據div的寬度計算要顯示的圖像的數量,假設寬度爲1200px,每個圖像的大小爲150px。所以要顯示的圖像數量是8。

<script type='text/javascript'> 
var screen_width = document.getElementById('div_1').offsetWidth(); 
var no_of_images =Math.round(screen_width/100); 
</script> 

我從MySQL數據庫中獲取圖像,使用限制查詢..我想它限制在圖像的我得到了使用VAR no_of_images。但是,因爲他們沒有將JavaScript變量集成到mysql查詢中的直接規則。我想將它傳遞給PHP變量,然後在Mysql中使用它。但不幸的是,我不知道該怎麼做。

回答

1

您可以使用document.ready事件處理程序來確保DOM已準備好進行操作,然後向您的服務器端腳本發出AJAX請求,以便將正確數量的圖像輸出到容器中的HTML:

//wait for the `document.ready` event to fire 
$(function() { 

    //cache the container element since it will be used later more than once 
    //also get the width of the container and figure out how many 150px wide images can fit without being clipped 
    //note that this does not take into consideration any padding/margin/border for the images 
    var $container = $('#div_1'), 
     screen_width = $container.width(), 
     no_of_images = Math.floor(screen_width/150); 

    //create an AJAX call to your server-side script to get the image HTML 
    $.ajax({ 
     url : '<URL>', 
     type : 'get',//or 'post' 
     data : { 'no_of_images' : no_of_images },//jQuery will handle data encoding if you pass it an object 
     success : function (serverResponse) { 

      //now the AJAX request has returned successfully so this fades the container out, replaces it's HTML with the server response and then fades back in 
      $container.fadeOut(500, function() { 
       $container.html(serverResponse).fadeIn(500); 
      }); 
     }, 

     //if an error occurs with the AJAX call this is how you handle it, you may just try to re-send the AJAX call 
     error : function() { 
      alert('an error occured'); 
     } 
    }); 
}); 
+0

Thxx Jasper ..它的工作:) – 2012-02-05 11:40:46

0

加載頁面時,您可以將它作爲get參數傳遞。例如當創建鏈接加載下一頁時,只需將其添加爲參數即可。在初始頁面加載你得到所有的圖像埠只顯示你需要的分辨率

+0

我知道這一點,但真的那不是我所需要的。有沒有什麼辦法可以在PHP中獲得div的偏移寬度。然後我可以解決我的問題 – 2012-02-05 11:28:08

+0

不,你不能從PHP訪問。 PHP運行在服務器上,客戶端的JavaScript。通過重新加載頁面或進行ajax調用 – clem 2012-02-05 11:31:12

0

你必須使用AJAX。

<script type='text/javascript'> 
    var screen_width = document.getElementById('div_1').offsetWidth(); 
    var no_of_images =Math.round(width/100); 

    $.ajax({ 
     type: "post", 
     url: "script.php", 
     data: "no_of_images="+no_of_images, 
     success: function(){ 
      // do something 
     } 
    }); 
</script> 

你必須使用jQuery來讓我的代碼工作,因爲我使用了jQuery方法$ .ajax()。