我试图了解 jQueryMobile 导航中的页面事件,但我发现了一些非常奇怪的行为,因为一些事件处理程序被多次调用:
我有两个页面:home.html 和 disclaimer.html。两者都包含相同的标题:
<head>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/events.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
</head>
在 home.html 页面上有一个链接:
<section data-role="page" id="home">
<a href="#" id="test">Test</a>
</section>
在文件 events.js 中是以下代码:
var i = 0;
$(document).on('pageinit', 'section#home', function(event) {
console.log(i++, 'pageinit');
$('a#test').on('click', function() {
console.log(i++, 'click pageinit');
});
});
$(document).on('pagebeforeshow', 'section#home', function(event) {
console.log(i++, 'pagebeforeshow');
$('a#test').on('click', function() {
console.log(i++, 'click pagebeforeshow');
});
});
然后我执行以下步骤:
- 导航到 home.html (http)
- 点击链接
- 转到 disclaimer.html (ajax)
- 转到 home.html (ajax)
- 点击链接
使用以下控制台输出:
0 "pageinit" // step 1
1 "pagebeforeshow"
2 "click pageinit" // step 2
3 "click pagebeforeshow"
4 "pagebeforeshow" // step 4
5 "click pageinit" // step 5
6 "click pagebeforeshow"
7 "click pagebeforeshow"
有道理,对吧?但现在奇怪的部分。当我更改访问页面的顺序时:行为会发生变化。
- 导航到 disclaimer.html (http)
- 转到 home.html (ajax)
- 点击链接
- 转到 disclaimer.html (ajax)
- 转到 home.html (ajax)
- 点击链接
控制台输出:
0 "pageinit" // step 2
1 "pagebeforeshow"
2 "click pageinit" // step 3
3 "click pagebeforeshow"
4 "pageinit" // step 5
5 "pagebeforeshow"
6 "click pageinit" // step 6
7 "click pagebeforeshow"
这很奇怪,因为我希望第 6 个和第 7 个结果被重复。
对不起,很长的问题。我希望有人能准确地向我解释发生了什么,如果这是预期的行为?
tldr; 你在哪里监听 jQueryMobile 中的(点击)事件?