我知道当您使用 ajax 使用 jquery mobile 切换页面时,它只会使用data-role="page"
. 问题是这是一个在移动设备上运行的 phonegap 应用程序,因此在没有 ajax 的情况下进行全页面加载对于获取所有 JS、CSS 脚本来说非常慢。
我一直在寻找尝试不同的东西。文档说您可以将 javascript 附加到 dom 并将其放在data-role="page"
元素下,但我仍然无法以这种方式触发它。
我目前正在尝试的是在第一页顶部包含一个引导脚本,并且在 pagechange 上它尝试在 dom 中插入特定于该页面的 js
function insertScript(script, container) {
var elem = document.createElement('script');
elem.type = 'text/javascript';
elem.src = 'Assets/Scripts/' + script + '.js';
container.appendChild(elem);
}
$(document).bind('pagechange', function(event){
//get the path to the html asset
var path = document.location.pathname;
//split up
var arr = path.split('/');
//get the relevant part of the path ie index.html
var page = arr[arr.length-1];
// grab a list of all the divs's found in the page that have the attribute "role" with a value of "page"
var pages = $('div[data-role="page"]'),
// the current page is always the last div in the Array, so we store it in a variable
currentPage = pages[pages.length-1];
//if the page is index add index.js to the last dom node
if (page == 'index.html') {
insertScript('index', currentPage);
}
});
然后例如 index.js 有以下
$("#start_page").live('pageinit', function() {
alert('on start page');
});
但是 pageinit 函数永远不会触发。有任何想法吗
**编辑:
我有多个 html 页面,例如使用 index.html 和 home.html
*index.html
<html>
<head>
<script type="text/javascript" src="js/phonegap-1.3.0.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.0.min.js"></script>
<script type="text/javascript">
$("#index_page").live('pageinit', function() {
//do some page specific js functions for index.html
});
</head>
<body>
<div data-role="page" id="index_page">
<a href='home.html'>go to home page</a>
</div>
</body>
</html>
**home.html
<html>
<head>
<script type="text/javascript">
$("#home_page").live('pageinit', function() {
//this is the JS I want to pull
});
</head>
<body>
<div data-role="page" id="home_page">
<h1>this is the home page</h1>
</div>
</body>
</html>
因此,当我单击从索引到主页的链接时会发生什么,dom 会更新,但是 home.html 页面上的任何 JS 都不会通过 AJAX 插入到页面中,所以我试图找出一种方法来做到这一点。
我知道我可以将我所有的 js 包含在一个页面中,但我真的想避免这种情况,因为我有很多页面,它会很快变得混乱。