1

我知道当您使用 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 包含在一个页面中,但我真的想避免这种情况,因为我有很多页面,它会很快变得混乱。

4

3 回答 3

1

请记住,当 jQuery Mobile 通过 AJAX 加载另一个页面时,它所做的只是将<div data-role="page">新页面中的<body>. 外面的任何东西都div可能不存在。因此,当您拉入第二页时,您要插入的脚本实际上并不存在。

你可以这样做的方法是 - 将脚本包含在页面 div 中,或者将所有 javascript 加载到 HEAD 中。你也应该注意这点小智慧

http://code.jquery.com/mobile/latest/demos/docs/api/events.html

“为了在初始页面加载期间调用这些处理程序,您必须在 jQuery Mobile 执行之前绑定它们。这可以在 mobileinit 处理程序中完成,如全局配置页面所述。”

哦,还有一件事要记住......将javascript复制到已经加载的页面中实际上不会执行它;)

于 2012-01-21T02:26:06.990 回答
0

不确定您要完成什么,但您可以使用 javascript 遍历页面上的每个链接并将 onclick 设置为返回 false,但将 href 转发到 ajax 调用。php页面会接收到请求页面的url,解析xml,返回body的内容。然后这可以替换第一页的正文。

于 2012-01-21T00:15:06.950 回答
0

我还遇到了问题。最后我使用iframe标签并添加到data-role="page"页面 div 中。

像这样:

<iframe style="display:none" onload="javascript:js_fun()"></iframe>

然后js_fun()运行。因此可以通过ajax加载js代码或文件。

于 2013-06-10T04:42:13.157 回答