我正在撕掉我的头发。我是jQuery Mobile的新手,当浏览器滚动到页面底部时,我有一个可以加载新内容的函数。与jQuery Mobile的AJAX调用 - 为什么方法被调用两次?
我也有一个在哪里你可以选择类别。它在起始页面上工作正常(即没有选择类别)。但是,只要我选择一个类别,然后滚动到底部,功能bindScroll()就会触发两次。
我一直在为此工作近两天,试图找到一些解决方案,但没有。我还没有真正弄清楚不同的jQuery Mobile事件,因此可能存在一些问题。
请看我的代码和帮助,如果你可以。该网站建立在.NET MVC中,但问题在于jQuery。
@using Namespace.Helpers
@{
ViewBag.Title = "Home Page";
}
@Html.Raw(Html.GetCategories(true, "CategoryId", 0, true))
// 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();
}
}
}
编辑答案: -------------------------------------- ---------
我从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;
}
}
}
}
而在Ajax调用的success:设置scrollHappening = false。似乎工作相当不错!