如何在jQuery Mobile中绑定"mobileinit"事件?

13

这是我尝试挂钩到mobileinit事件的方式:

$(document).bind("mobileinit", function() {
    console.log("Mobile init");
});

但是在Chrome(最新版本)、Ripple v0.9.1和运行OS7.0的BlackBerry bold 9790上无法工作。

注意: 我也尝试使用.on()代替.bind(),但没有成功。两个jQuery Mobile版本(1.0.1和1.1.0)都失败了。

2个回答

47

我使用过这个方法,它确实有效

有可能是其他东西破坏了脚本,或者mobileinit事件没有被触发吗?

Chrome会触发mobileinit事件吗?

我刚刚找到了一些我在jQuery Mobile 1.0中使用的代码,我们刚刚升级到1.1.0,它可以工作。

你确定还包括普通的jQuery库吗?

jQueryMobile的文档也是这么做的,所以我确定它是有效的。其他问题肯定出在别处了。很抱歉我没能提供更多帮助。你有更多信息吗?或尝试另一个设备。

[编辑] 在同一页上,它说“因为mobileinit事件立即触发,所以必须在加载jQuery Mobile之前绑定事件处理程序。按照以下顺序链接JavaScript文件:”

<script src="jquery.js"></script>
<script src="custom-scripting.js"></script> <!-- Note your script before jqm -->
<script src="jquery-mobile.js"></script>

看起来脚本的顺序很重要。


3
custom-scripting.js 文件将存储您的 mobileinit 事件处理程序,以便在 jQuery Mobile 初始化时绑定它(并触发 mobileinit 事件)。 - Jasper
我在文档中读到过这个,所以我知道这个问题,但它仍然让我感到困惑。非常感谢您的帖子,节省了我好几个小时! - Dave R
@DaveR 我知道这完全是题外话,但自从四月以来我就没怎么用过jQuery Mobile了。在你评论的同一天,我正在使用jQM编译一个使用PhoneGap完成的应用程序。不管怎样,很高兴能帮到你! - CWSpear
Ugh和Gack。感谢您发布这个。 - fool4jesus

5

这是另一个与我一起配合(适用于Android和iOS)的简单示例:

<script type="text/javascript" src="files/resources/lib/jquery/jquery-1.8.2.js"> </script>
<script type="text/javascript">
$(document).bind("mobileinit", function()
                 {
                 if (navigator.userAgent.toLowerCase().indexOf("android") != -1)
                 {
                 // your logic here
                 $.mobile.defaultPageTransition = 'none';
                 $.mobile.defaultDialogTransition = 'none';
                 }
                 if (navigator.userAgent.toLowerCase().indexOf("msie") != -1)
                 {
                 // your logic here
                 $.mobile.allowCrossDomainPages = true;
                 $.support.cors = true;
                 }
                 });
</script>
<script type="text/javascript" src="files/resources/lib/jquerymobile/1.3.2/jquery.mobile-1.3.2.js"></script>
  1. 引入主要的jquery文件
  2. 在引入jquery mobile之前绑定mobileinit事件
  3. 引入jquery mobile js文件

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接