如何在$ .mobile.changePage在jquery中准备好后运行回调函数?

Pat*_*cow 7 javascript jquery jquery-mobile cordova

在这个项目中我使用jquery和phonegap

我有一个链接,如果点击,更改页面:

$('#statsButtonmain').on('click', function() {
        $.mobile.changePage("stats.html", { transition: "slideup"}, true, true);  
});
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我想playMusic()在转换完成后运行一个函数(),如下所示:

$('#statsButtonmain').on('click', function() {
        $.mobile.changePage("stats.html", { transition: "slideup"}, true, true);  
            playMusic();
});
Run Code Online (Sandbox Code Playgroud)

我发现有一个pageshow事件在转换完成后显示在页面上被触发,但我不知道如何使用它

这似乎不起作用,任何想法?

谢谢

and*_*dyb 4

我没有做过很多 jQuery 移动开发,所以这可能不是最有效的解决方案。正如你所说,pageshow事件就是你需要使用的。stats.html以下是我在本地运行的 2 个 HTML 文件,在页面转换完成后我在其中看到了警报。绑定.live()#stats元素的页面pageshow事件。

超文本标记语言

(另存为index.html)

<!doctype html> 
<html> 
  <head> 
    <title>Home</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#statsButtonmain').on('click', function() {
           $.mobile.changePage('stats.html', { transition: 'slideup'}, true, true);  
        });

        $('#stats').live('pageshow', function(event, ui) {
          playMusic();
        });

        function playMusic() {
          alert('playing music');
        }
    });
    </script>
</head> 
<body>
<div data-role="page" id="home">
    <div data-role="header">
       <h1>Callback test</h1>
    </div>
    <div data-role="content">
      <a href="#" id="statsButtonmain">click me</a>
    </div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

(另存为 stats.html)

<!doctype html> 
<html> 
  <head> 
    <title>Stats</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
</head> 
<body>
<div data-role="page" id="stats">
    <div data-role="content">some stats</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 向大家发出警告:“live”已被弃用,并且已从 jQuery 1.9 中删除。我建议使用“delegate”或“on”代替。有关详细信息,请参阅 http://api.jquery.com/live/。 (2认同)