我在这个上扯掉我的头发。我是 jQuery Mobile 的新手,我有一个功能可以在浏览器滚动到页面底部时加载新内容。
我还有一个<select>
你可以选择类别的地方。它在起始页上运行良好(即没有选择类别时)。但是一旦我选择了一个类别,然后滚动到底部,该功能bindScroll()
就会触发两次。
我已经为此工作了将近两天,试图找到一些解决方案,但什么也没有。我还没有真正弄清楚不同的 jQuery Mobile 事件,所以那里可能存在一些问题。
如果可以,请查看我的代码并提供帮助。该站点是在 .NET MVC 中构建的,但问题在于 jQuery。
@using Namespace.Helpers
@{
ViewBag.Title = "Home Page";
}
<!-- Get a drop down of the different categories -->
@Html.Raw(Html.GetCategories(true, "CategoryId", 0, true))
<!-- list view to append the fetched ads to -->
<ul data-role="listview" data-inset="true" id="ad-list">
</ul>
<script>
// keeps track of how many rows to skip in the db. this is passed along to the server side
var currentPos = 0;
// save the categoryId
var categoryId = $('#CategoryId').val();
$('#page-start').live('pagecreate', function () {
// load the ads for the first call
loadAds();
//handle the category drop down
$('#CategoryId').change(function () {
// clear the list of ads
$('#ad-list').empty();
// reset so we start fetching from the first row in the db, used on server side
currentPos = 0;
// update the category value to pass along to the server
categoryId = $('#CategoryId').val();
// just to know that it has a value
console.log(categoryId);
// re-load the new ads
loadAds();
});
});
// method that loads ads via AJAX
function loadAds() {
console.log('loadAds()');
$.ajax({
// method on the server that returns a partial view
url: '/Home/LoadMoreAds',
type: 'GET',
data: {
// pass along some data
currentPosition: currentPos,
categoryId: categoryId
},
success: function (result) {
// add the result to the ad-list
$('#ad-list').append(result);
$('#ad-list').listview('refresh');
// once again, bind the scroll event
$(window).scroll(bindScroll);
},
error: function (data, textStatus, jqXHR) {
alert(textStatus);
}
});
}
// method that checks if the scroll is near the bottom of the page
function bindScroll() {
if($(document).height() > $(window).height())
{
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$(window).unbind('scroll');
// just to know that the method has run
console.log('bindScroll()');
// update counter to skip the already loaded rows
currentPos++;
// load new ads
loadAds();
}
}
}
</script>
编辑后的答案:---------------------------------------------------------
我接受了 Mike C 的建议,不绑定并重新绑定滚动事件。页面初始化时只有一个绑定。然后我使用了这段代码:
// method that checks if the scroll is near the bottom of the page
var scrollHappening = false;
function bindScroll() {
if (scrollHappening) {
return false;
} else {
if ($(document).height() > $(window).height()) {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
// just to know that the method has run
console.log('bindScroll()');
// update counter to skip the already loaded rows
currentPos++;
// load new ads
loadAds();
scrollHappening = true;
}
}
}
}
并设置scrollHappening = false
在success:
ajax 调用中。似乎工作得很好!