我正在使用主题标签创建一个包含多个页面的 JQM 网站。例如index.html#a 在其中一个页面上,我需要初始化一张 map ,例如index.html#map。但我突然想到,无论我将 map 初始化脚本放在哪里,当index.html首次加载时该脚本仍然会被执行,这是我想避免的。
虽然我可能会将 map 脚本与某些按钮相关联,但我也希望能够在有人直接加载index.html#map时加载 map 。
那么归根结底就是如何将 JavaScript 与子页面(带有话题标签的页面)关联起来?
最佳答案
我希望所有这些页面都是单个 HTML 文件的一部分。如果我是正确的,您不需要使用此语法:
index.html#map
这个就足够了:
#map
假设这是您的 HTML:
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
<a href="#second" class="ui-btn-right">Next</a>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>
Second Page
</h3>
<a href="#index" class="ui-btn-left">Back</a>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
</body>
</html>
然后使用以下语法将 JavaScript 关联到某个页面:
$(document).on('pagebeforeshow', '#index', function(){
alert('Index page');
});
$(document).on('pagebeforeshow', '#second', function(){
alert('Second page');
});
这是一个工作的 jsFiddle EXAMPLE 。
也可以看看我的个人博客 ARTICLE ,它将帮助您处理 jQuery Mobile 页面事件。或者看看我的另一个ANSWER .
关于jQuery mobile : page specific javascript, 主题标签页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562681/