您知道 JQM 开发人员提供了一个插件用于此目的:JQM pagination
我认为您的问题与多个绑定有关。
在每个绑定中添加console.log 以查看它触发的频率。像这样:
$('body').live('pagecreate', function(event) {
console.log( "PAGECREATE fired")
$('div[data-role="page"]').live("swipeleft", function() {
console.log("binding to swipe-left on "+$(this).attr('id') );
var nextpage = $(this).next('div[data-role="page"]');
// swipe using id of next page if exists
if (nextpage.length > 0) {
$.mobile.changePage(nextpage);
}
});
$('div[data-role="page"]').live("swiperight", function() {
console.log("binding to swipe-right "+$(this).attr('id');
var prevpage = $(this).prev('div[data-role="page"]');
// swipe using id of previous page if exists
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, {
reverse : true,
});
}
});
});
如果这些触发不止一次,您将附加多个绑定到您的页面,当您只想在每次滑动时触发 one 事件时,all 会在滑动时触发 changePage。
编辑:
首先,如果您使用的是最新的 Jquery,您应该使用 on/off 进行绑定,而不再使用 live。
一种方法是在重新加载页面时在pagehide 上发送unbind 并重新发送bind。我想这将是推荐的方式。但是,如果您在滑动到下一页时没有从 DOM 中删除页面,您将解除绑定,并且由于 pagecreate 不会再次触发(页面仍在 DOM 中,无需创建),您将不会再次 bind当您向后滑动时。
我也经常处理这个问题并且正在使用这个:
$(document).on('pageshow', 'div:jqmData(role="page")', function(){
var page = $(this), nextpage, prevpage;
// check if the page being shown already has a binding
if ( page.jqmData('bound') != true ){
// if not, set blocker
page.jqmData('bound', true)
// bind
.on('swipeleft.paginate', function() {
console.log("binding to swipe-left on "+page.attr('id') );
nextpage = page.next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.changePage(nextpage);
}
})
.on('swiperight.paginate', function(){
console.log("binding to swipe-right "+page.attr('id');
prevpage = page.prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, {
reverse : true,
});
};
});
}
});
这将与每个pageshow 一起触发,并检查页面是否为bound。如果没有,它会在此页面上设置绑定。下一次pageshow 触发bound 将是真的,所以它不会重新绑定。如果页面从 DOM 中移除并重新加载,bound 将不会被设置并且绑定将被重置。
我还在您的 swipeleft/swiperight 中添加了 .paginate,因此您可以使用 off 一次性删除它们