1

I created a simple webapp using jQuery Mobile 1.2. This app consists of a main page index.html and a second page named settings.html. The main page contains a button in the header section to open the settings page:

<div data-role="header">
    <h1>Main</h1>
    <a href="settings.html">Settings</a>
</div><!-- /header -->

In the settings dialog the user should be able to change program options. For this purpose I implemented a function to set the current options every time the dialog opens:

$(document).on("pageinit", "#page-settings", function() {
    // numeric text field to change the year of date (settings is an array)
    $("#text-year").val(settings.year);
    ...
});

That works correct so far.

Now I read that there are some more events like "pagebeforeshow" and "pageshow". But I don't understand the difference between these events. I tested the triggers as follows:

$(document).on("pageinit", "#page-settings", function() {
    alert("pageinit");
});
$(document).on("pagebeforeshow", "#page-settings", function() {
    alert("pagebeforeshow");
});
$(document).on("pageshow", "#page-settings", function() {
    alert("pageshow");
});

If I click the button on the main page then all three events will fire and all alerts will display. So why there are different events? And which one should I use in my settings scenario?

I thought that the process is the following: I go to my index page the first time, all elements on that page are added to the DOM and then the events pageinit and pageshow for index are fired. Then I click the link and change to the settings page, all elements of the settings page are added to the DOM and the events pageinit and pageshow for settings are fired. So far okay. Then I go back to the index page. Beacuse the index elements are still in DOM, only the pageshow event is firing. Then I click the settings link again. The settings elements should also be in DOM, so only pageshow should firing again. But the problem is that all events are fired everytime I change a page. So the question is: Why are there different events? And where should I place the filling of text boxes or the triggers of button clicks?

4

1 回答 1

3
  • 当 DOM 准备好时触发“pageinit”。当您想在下载页面时初始化变量时,此选项非常有用。

  • “pagebeforeshow”在您的页面显示之前触发。
    当您需要在显示之前执行操作时,您可以使用此事件,
    例如添加 div 或 HTML 结构。

  • “pageshow”在页面显示时触发。我使用这个事件来添加我的点击事件和其他事件。

您可以在文档中找到有关事件的更多信息:http: //api.jquerymobile.com/category/events/

于 2013-03-20T21:48:56.103 回答