【问题标题】:phonegap ios - jquery not workingphonegap ios - jquery 不工作
【发布时间】:2015-11-20 12:58:04
【问题描述】:

当我在页面中放置带有 jQ​​uery 的脚本标签时,$('body') 的结果是空数组。并且 Safari 控制台中没有错误。 我试图将它粘贴到正文中,在cordova.js之前和之后的头部,尝试从CDN加载它并加载本地文件,结果相同。 在 Android 上一切正常。

我的代码:

<!DOCTYPE html>
<html lang="en" ng-app="wApp">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>Page</title>
  <link rel="stylesheet" href="app.css">
  <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
  <script type="text/javascript" charset="utf-8" src="libs/jquery.js"></script>
<script>
 console.log("jQuery: ", jQuery, $);
 $(function() {
   console.log('Dom Ready');
   console.log('Body element: ', $('body'));
 });
</script>
</head>
<body>
 //// HTML content here
 //// Angular scripts here
</body>
</html>

这段代码在模拟器上运行时的控制台结果是:

jQuery: function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
        }
Dom Ready
Body element: []

我尝试一一删除其他脚本,只有 jQuery 脚本会影响此行为。并且仅在 iOS 中。

【问题讨论】:

  • 您必须等待 cordova deviceready 事件。阅读文档。

标签: javascript jquery ios cordova phonegap-build


【解决方案1】:

每当您加载应用程序时,Cordova 都会创建自己的视图,有点像 Web 视图,因此不会立即创建。为了解决这个问题,cordova 在 DOM 加载时触发 deviceready 事件。要得到这个,请使用document.addEventListener("deviceready", yourCallbackFunction, false);

所以&lt;head&gt; 标记中的脚本应该如下所示:

function deviceLoaded() {
    console.log("jQuery: ", jQuery, $);
    $(function() {
        console.log('Dom Ready');
        console.log('Body element: ', $('body'));
    });
}

document.addEventListener("deviceready", deviceLoaded, false);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多