我使用带有持久标头的多页格式。我可以使用直接超链接或使用$(':mobile-pagecontainer')成功更改页面.pagecontainer('change'
代码工作正常,但每次单击按钮更改页面时,它似乎会再次“加载”页面。 在此代码中,按钮更改页面并输出console.log消息。 点击后,我希望页面可以更改并查看一个“#btn - page x”console.log消息。 页面发生了变化,我收到了每个时间加载页面的控制台消息,而不仅仅是一个。 即使我的代码工作正常,这也不对 - 这只会随着用户的正常使用而增加。
我在这里不理解什么?
我创建了jsfiddle以显示我的意思。例如,如果我单击“转到页面x”按钮6次(每页3次),我得到3“#btn - page x”消息的输出,而不仅仅是一个。
与标题按钮相同 - 每次更改页面时,标题按钮的响应数量都会增加。
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>problem</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="header" data-position="fixed" data-theme="a">
<a href="#" data-role="button" id="headerbtn">header button</a>
</div>
<div data-role="page" id="page1" data-title="Page 1">
<div data-role="content">
<h1>I am page 1</h1>
<a href="#page2" data-role="button" id="btntest1">goto page2</a>
</div>
</div>
<div data-role="page" id="page2" data-title="Page 2" data-theme="b">
<div data-role="content">
<h1>I am page 2</h1>
<a href="#page1" data-role="button" id="btntest2" data-rel="back">goto page1</a>
</div>
</div>
<script src="problem.js"></script>
</body>
</html>
和js:
$(document).on('pagebeforeshow','#page1',function(){
console.log('#page1 pagebeforeshow');
$('#btntest1').click(function(){
console.log('#btn - page1');
//$(':mobile-pagecontainer').pagecontainer('change', '#page2', { reloadPage: false});
});
});
$(document).on('pagebeforeshow','#page2',function(){
console.log('#page2 pagebeforeshow');
$('#btntest2').click(function(){
console.log('#btn - page2');
//$(':mobile-pagecontainer').pagecontainer('change', '#page1', { reloadPage: false});
});
});
$(function() {
$("[data-role='header']").toolbar();
});
$(document).on('pagebeforeshow',function(){
console.log('pagebeforeshow');
$('#headerbtn').click(function(){
console.log('headerbtn click');
});
})
更新:
所以我一直在尝试各种各样的事情来尝试解决这个问题,包括删除data-rel =“back”,尝试data-ajax =“false”(这使我想要做的事情失败了),改变了页面
$(':mobile-pagecontainer').pagecontainer('change', '#page2');
或
$(':mobile-pagecontainer').pagecontainer('change', '#page2', { reloadPage: false});
但没有快乐。显然,我已经尝试使用谷歌搜索,但找不到任何帮助。
在完整的应用程序代码中,按钮与数据库通信,因此随着点击次数的增加,我每次点击都会多次向数据库发送和检索相同的数据。
如果有人有任何想法,我真的很感激一些指导吗?
答案 0 :(得分:1)
问题在于,每次进入页面时,都会再次绑定元素上的侦听器。所以你绑定了多个听众。不应将监听器写入pagebeforeshow
处理程序。
像这样把它拿出来:
$(document).on('pagebeforeshow','#page1',function(){
console.log('#page1 pagebeforeshow');
});
$('#btntest1').click(function(e){
e.preventDefault();
console.log('#btn - page1');
$(':mobile-pagecontainer').pagecontainer('change', '#page2', { reloadPage: false});
});
同样适用于第2页。