我在jQuery和jQuery mobile上使用了Onsen框架,看起来没有办法捕获新页面加载后触发的事件。在Onsen上的onsen pageinit后无法访问DOM元素
我当前的代码,其中执行在index.html文件(主页)
<script src="scripts/jQuery.js"></script>
<script src="scripts/jquery.mobile.custom.min.js"></script>
<script src="scripts/app.js"></script>
<script>
ons.bootstrap();
ons.ready(function() {
$(document.body).on('pageinit', '#recentPage', function() {
initRecentPage();
});
});
在app.js
是下面的代码
function initRecentPage() {
$("#yourReports").on("tap", ".showReport", recentShowReport);
var content = document.getElementById("yourReports");
ons.compile(content);
}
和HTML:
<ons-page id="recentPage">
<ons-toolbar id="myToolbar">
<div id="toolBarTitle" class="center">Recent Checks</div>
<div class="right">
<ons-toolbar-button ng-click="mySlidingMenu.toggleMenu()">
<ons-icon icon="bars"></ons-icon>
</ons-toolbar-button>
</div>
</ons-toolbar>
<ons-scroller>
<h3 class="headingTitle"> Checks</h3>
<div id="Free" class="tabArea">
<ons-list id="yourReports">
</ons-list>
<ons-button id="clearFreeRecentButton">
<span id="clearRecentText" class="bold">Clear Recent Checks</span>
</ons-button>
</div>
</ons-scroller>
</ons-page>
在这种情况下,变量'content'始终为空。我已经大打出手了,当这个事件发生时,我想要获得的元素不存在。它稍后加载。
所以,问题是,在使用选择器之前,如何确保所有内容都存在。感觉这是一个特殊的温泉问题。
感谢您试图帮助,但这也不起作用。我看到这是如何在codepen中工作的,但是在多页应用程序中(使用monaca构建im),这不起作用。 如果我将代码移到ons.ready之外,则什么都不会触发。至少在ons.ready函数中,我得到了一个回调,即使DOM元素没有正确加载。 我想看看它是否与页面打开的方式有关,目前它是通过-ySlidingMenu.setMainPage('recent.html',{closeMenu:true})打开的,也许这是干扰与DOM加载。缺乏文档是一种痛苦。 – Deej 2014-10-18 15:04:08
它应该工作...也许它被缓存?我一直在Monaca的multipira项目上做这件事。 – 2014-10-19 00:48:17
再次感谢Vu的帮助。这个问题没有解决,但我发现了一些事情。如果我将$(document.body).on函数更改为$(document)。在回调函数触发时,奇怪的是。其次,我认为这个问题与页面打开的方式有关。它通过调用 - ySlidingMenu.setMainPage('recent.html',{closeMenu:true})从菜单打开。现在,这会触发回调,但html元素不存在。我认为这与菜单隐藏的方式有关,然后显示内容。如果我放入一个简单的setTimeout并等待100毫秒,那么元素就在那里 – Deej 2014-10-20 09:25:46