使用jQuery Mobile,onload函数不会在HTML中触发

use*_*803 4 html javascript jquery jquery-mobile

我有一个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>
Run Code Online (Sandbox Code Playgroud)

然后我有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>
Run Code Online (Sandbox Code Playgroud)

onload函数没有启动....如果我尝试刷新页面(occassion.html)然后onload函数被激活...为什么它导航时不工作index.html

如果我删除jQuery文件,那么它按预期工作....我想要添加什么?

这也行不通

 $(document).ready(function () {
        loaded();
    });
Run Code Online (Sandbox Code Playgroud)

编辑

我补充道

 <script>
    $(document).bind("pagechange", function (event, data) {
        console.log(data);
        var toPage = data.toPage[0].id;
        alert(toPage);
        if (toPage == "page2")
            alert("hello");
    });
</script>
Run Code Online (Sandbox Code Playgroud)

并将以下内容放在occassion.html中

<div data-role="page" id="page2">
 hello
 </div>
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,连警报(你好)都没有开火,但也没有显示你好,并且警报(topage)空无一人.

如何?少了什么东西

Jas*_*per 9

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);
Run Code Online (Sandbox Code Playgroud)

请注意,这#occasions将是data-role="page"场景页面中的元素.