我知道当你用jquery mobile使用ajax切换页面时,它只会抓取data-role="page"
中的DOM。问题是这是一个在移动设备上运行的phonegap应用程序,所以在不使用ajax的情况下进行整页加载非常缓慢,获取所有JS,CSS脚本。有没有办法在jquery mobile ajax负载上抓取javascript
我一直在四处寻找不同的东西。文档说你可以将javascript附加到dom中,并将它放在一个data-role="page"
元素下,但我仍然无法通过这种方式启动它。
什么我目前想是有被包含在第一页的顶部和pagechange在试图插入特定于该页面中的JS在DOM
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会更新,但任何JS o在home.html页面不会通过AJAX插入页面,所以我试图找出一个方法来做到这一点。
我知道我可以将所有的js包含在一个页面中,但我真的很想避免这种情况,因为我有很多页面,并且它会变得很乱。
我在问题中添加了一些信息以更好地布置我所要求的内容。基本上我想在使用ajax导航时引入页面特定的javascript – Brian