我试图在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();
});
后面的代码不是那么有趣,它只是以这种格式从DB中返回数据(每次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表正确实现它并使其工作的任何建议。
可能是因为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
正在移动到它之外。
IMO,真的不需要div
里面的table
。试试这是否有效:
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();
}