2014-10-16 49 views
1

我在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'始终为空。我已经大打出手了,当这个事件发生时,我想要获得的元素不存在。它稍后加载。

所以,问题是,在使用选择器之前,如何确保所有内容都存在。感觉这是一个特殊的温泉问题。

回答

1

最后我只能找到一个可靠的方法来完成这项工作。 本质上,我不得不等待,使用setTimeout 300毫秒准备DOM元素。这感觉就像一个黑客,但老实说,没有其他可靠的方式来做到这一点。该应用程序在应用程序商店,并运行良好,所以即使它看起来像一个黑客,它的工作原理:

$(document).on('pageinit', '#homePage', function() { 
     initHomePage(); 
    }); 

function initHomePage() { 
setTimeout(function() { 
    setUpHomePage(); 
}, 300); 
} 
0

将您的$(document.body).on('pageinit', '#recentPage', function() {移至ons.ready区块之外。

JS

ons.bootstrap(); 
ons.ready(function() { 
    console.log("ready"); 
}); 

$(document.body).on('pageinit', '#recentPage', function() { 
      initRecentPage(); 
}); 

function initRecentPage() { 

//$("#yourReports").on("tap", ".showReport", recentShowReport); 
var content = document.getElementById("yourReports"); 
    alert(content) 
ons.compile(content); 
} 

我注释掉一条线,因为我没有访问该 “recentShowReport”

你可以看到它是如何工作在这里: 'http://codepen.io/vnguyen972/pen/xCqDe'

的警报将显示“内容”不是NULL。 希望这有助于。

+0

感谢您试图帮助,但这也不起作用。我看到这是如何在codepen中工作的,但是在多页应用程序中(使用monaca构建im),这不起作用。 如果我将代码移到ons.ready之外,则什么都不会触发。至少在ons.ready函数中,我得到了一个回调,即使DOM元素没有正确加载。 我想看看它是否与页面打开的方式有关,目前它是通过-ySlidingMenu.setMainPage('recent.html',{closeMenu:true})打开的,也许这是干扰与DOM加载。缺乏文档是一种痛苦。 – Deej 2014-10-18 15:04:08

+0

它应该工作...也许它被缓存?我一直在Monaca的multipira项目上做这件事。 – 2014-10-19 00:48:17

+1

再次感谢Vu的帮助。这个问题没有解决,但我发现了一些事情。如果我将$(document.body).on函数更改为$(document)。在回调函数触发时,奇怪的是。其次,我认为这个问题与页面打开的方式有关。它通过调用 - ySlidingMenu.setMainPage('recent.html',{closeMenu:true})从菜单打开。现在,这会触发回调,但html元素不存在。我认为这与菜单隐藏的方式有关,然后显示内容。如果我放入一个简单的setTimeout并等待100毫秒,那么元素就在那里 – Deej 2014-10-20 09:25:46