无限滚动(滚动加载)与HTML表格标签

3

我尝试在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个)从数据库返回数据(每行一个):

<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表格正确实现并使其工作的任何建议。


你是从 Web 服务获取头信息吗?还是它们是硬编码的?在你的示例代码中,它们是硬编码的,因此不应该移动到下面插入到它们下面的元素。 - abc123
2个回答

2
可能是因为HTML无效:tbody应该只包含tr为什么不直接将行附加到tr中,像这样?
<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);
这个JSBin比较了这种方法和您当前尝试的方法。通过Chrome的DOM检查器查看您的方式,似乎Chrome将
移动到之前。
被移动到外面。
我在JSBin中为表格添加了边框,以显示

谢谢您的建议,下周我会在我的工作电脑(内部网络)前尝试它。如果有效,我会标记为答案。 - ronlut

0
一个位于表格内的
在我看来并不是真正需要的。尝试看看这个是否可行: < p > 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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接