2013-01-31 62 views
2

我試圖在html表格上實現無限滾動或「滾動加載」(如果需要)。 數據存儲在數據庫中,我用後面的代碼訪問數據。使用html表格標籤的無限滾動(加載滾動)

我實現了從一個例子像在MSDN上:

JS

$(document).ready(function() { 

     function lastRowFunc() { 
      $('#divDataLoader').html('<img src="images/ajax-Loader.gif">'); 

      //send a query to server side to present new content 
      $.ajax({ 
       type: "POST", 
       url: "updates.aspx/GetRows", 
       data: "{}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (data) { 

        if (data != "") { 
         $('.divLoadedData:last').before(data.d); 
        } 
        $('#divDataLoader').empty(); 
       } 

      }) 
     }; 

     //When scroll down, the scroller is at the bottom with the function below and fire the lastRowFunc function 
     $(window).scroll(function() { 
      if ($(window).scrollTop() == $(document).height() - $(window).height()) { 
       lastRowFunc(); 
      } 
     }); 

     // Call to fill the first items 
     lastRowFunc(); 
    }); 

背後代碼不是那麼有趣,它只是從返回的數據(每次20行)此格式的DB(每行一個):

<tr><td>Cell 1 data</td><td>Cell 2 data</td><td>Cell 3 data</td></tr> 

ASPX

<table> 
<thead> 
    <tr><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr> 
</thead> 
    <tbody> 
     <div class="divLoadedData"> 
     </div> 
    </tbody> 
</table> 
<div id="divDataLoader"> 
</div> 

問題是,當數據被加載並插入到頁面(即使在第一負載)時,表頭在數據後。我看到我加載的所有行,但表頭位於頁面的底部(在我加載的20行之後)。 我嘗試一些變化插入加載的數據:

$('.divLoadedData:last').before(data.d); 

$('.divLoadedData:last').append(data.d); 

$('.divLoadedData:last').after(data.d); 

,但沒有一次成功。 很高興聽到有關如何正確使用html表實現它的任何建議,並使其工作。

+0

你從web服務獲得頭?或者他們是硬編碼的?在你的示例代碼中,它們是硬編碼的,因此不應該移動到任何插入到它們下面的元素下方的位置。 – abc123

回答

2

這可能是因爲HTML無效:tbody is only supposed to contain tr.爲什麼不直接追加行到tr,像這樣?

HTML

<table> 
<thead> 
    <tr><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr> 
</thead> 
<tbody class="tbodyLoadedData"> 
</tbody> 
</table> 
<div id="divDataLoader"> 
</div> 

JS

$('.tbodyLoadedData').append(data.d); 

This JSBin compares this way and the way you are currently trying。在Chrome的DOM檢查器中查看自己的方式,Chrome似乎將div移至table之前。

我在JSBin中的表格中添加了一個邊框,以顯示div正在移出它。

+0

感謝您的意見,下週我會在我的工作計算機(內聯網)前嘗試一下。 將標記爲答案如果作品當然 – RonLut

+0

對不起,忘了感謝你。它確實有效 – RonLut

0

A div裏面的table並不是真的需要,IMO。嘗試,如果這會工作:

ASPX:

<table> 
    <thead> 
    <tr><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr> 
    </thead> 
    <tbody class="divLoadedData"> 
    </tbody> 
</table> 
<div id="divDataLoader"> 
</div> 

成功回調:

function (data) { 
    if (data != "") { 
     $('.divLoadedData').append(data.d); 
    } 
    $('#divDataLoader').empty(); 
}