我有一个 index.html
文件,语法如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<a href="occassion.html">
<img class="frametoicon" src="img/occasion.png" />
</a>
</body>
</html>
然后我有 occassion.html
页面,其中有 body onload
功能如下
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Occassion</title>
<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/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
function loaded() {
alert("hii");
}
</script>
</head>
<body onLoad="loaded()">
</body>
</html>
但是 onload
函数没有启动....如果我尝试刷新页面 (occassion.html
) 然后 onload
函数被激发了...为什么从 index.html
导航时它不起作用?
如果我删除 jQuery 文件,那么它会按预期工作......我缺少添加什么?
这也行不通
$(document).ready(function () {
loaded();
});
编辑
我加了
<script>
$(document).bind("pagechange", function (event, data) {
console.log(data);
var toPage = data.toPage[0].id;
alert(toPage);
if (toPage == "page2")
alert("hello");
});
</script>
并将以下内容放入occassion.html
<div data-role="page" id="page2">
hello
</div>
令我惊讶的是,即使 alert(hello) 也没有触发,但 hello 也没有显示,而且 alert(topage) 变空了..
怎么样?缺少什么
最佳答案
jQuery Mobile 使用 AJAX 将页面拉入 DOM,这就是它在页面之间转换的方式。当 jQuery Mobile 执行此操作时,它很有可能在 window.load
事件触发后执行此操作,因此该事件通常不会触发,除非您刷新页面(然后 window.load
将再次触发)。用户似乎可以点击一个链接并在 window.load
事件触发之前加载它,但我不认为这是常态。
修复是使用 jQuery Mobile 特定事件,在这种情况下,您可能正在寻找 pageload
/pagecreate
/pageinit
,请参阅关于它们的文档在这里:http://jquerymobile.com/demos/1.2.0/docs/api/events.html
这是一个简单的示例,说明它是如何工作的(此代码将位于中心位置并包含在每个文档中):
$(document).on("pageinit", "#occasions", loaded);
请注意,#occasions
将是场合页面中的 data-role="page"
元素。
关于javascript - 使用 jQuery Mobile,onload 函数不会在 HTML 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14734675/