【问题标题】:Understanding jQuery-Mobile page firing events - why dialog pageshows when closing了解 jQuery-Mobile 页面触发事件 - 为什么关闭时显示对话框页面
【发布时间】:2014-04-04 17:41:48
【问题描述】:

我对 jQuery-Mobile 比较陌生,我正在尝试了解页面或对话框加载时发生的情况。

我创建了一小部分文件来说明我看到的奇怪现象。 请看https://github.com/kanesee/jqm-event

这个简单的例子只有一个打印 Hello World 的索引页面。有一个打开对话框的按钮,通过打开另一个页面,称为 dialog.html。每当任一页面触发 pageshow 或 pagehide 事件时,我都会打印出来。

这是动作的顺序。

  1. 打开 index.html:(索引的页面显示按预期触发)
  2. 单击对话框链接并弹出对话框:(然后触发以下事件序列:index pagehide、dialog pagehide、index pageshow、dialog pageshow)
  3. 关闭对话框:(索引页面隐藏、对话框页面隐藏、索引页面显示、对话框页面显示)

我不明白为什么对话框打开时会触发该序列。我了解索引页面隐藏,因为我们正在从索引页面过渡。不知道为什么对话框的页面隐藏接下来会触发。不知道为什么 index 的 pageshow 会触发。我明白为什么对话框的 pageshow 会最后触发。

我也不明白为什么在对话框关闭期间会触发序列。不知道为什么 index 的 pagehide 会触发。我明白为什么对话框 pagehide 会触发,然后 index pageshow 会触发。不知道为什么对话框 pageshow 会在最后再次触发。

如果有人能帮助解释这一系列奇怪的事件,我将不胜感激。 我看过这个序列图,但我不确定我是否完全理解它:http://bradbroulik.blogspot.co.nz/2011/12/jquery-mobile-events-diagram.html

【问题讨论】:

    标签: javascript jquery jquery-mobile dialog


    【解决方案1】:

    仅仅是因为pageshowpagehide 会在任何页面上触发。在您的代码中,您没有将事件委托给索引或对话框。这些事件绑定到 document,因此将在所有页面上触发。

    如果您执行以下操作,您会注意到不同之处。

    $(document).on("pageshow", "#index", function () {
      console.log("Page is shown");
    });
    

    它只会在索引页(带有id="index")可见时触发。


    更新

    在您的代码中,您没有将pageshowpagehide 附加到特定页面。当 data-role="page"data-role="dialog" 可见或隐藏时,这两个事件都会触发。

    在 index.html 中,您有以下代码。

    $(document).on('pageshow', '#indexpage', function(event) {
      console.log('pageshow index.html');
    });
    
    $(document).on('pagehide', '#indexpage', function(event) {
      console.log('pagehide index.html');
    });
    

    在启动时,将打印控制台日志

    pageshow index.html

    当您从 index.html 移动到 dialog.html(通过 Ajax)时,将打印控制台日志

    页面隐藏 index.html

    但在控制台日志打印pagehide index.html之前,dialog.html中的以下代码与HTML一起加载到DOM中并执行。

    $(document).on('pageshow', '#dialogPage', function(event) {
      console.log('pageshow dialog.html');
    });
    
    $(document).on('pagehide', '#dialogPage', function(event) {
      console.log('pagehide dialog.html');
    });
    

    因此,pagehide 在从 index.html 移动到 dialog.html 时会触发两次。此外,当从 dialog.html 移回 index.html 时,它会触发两次。此时,pageshow 也会触发两次。

    控制台日志将打印以下内容:

    1. 启动

      pageshow index.html

    2. 从 index.html 到 dialog.html

      页面隐藏 index.html -> 页面隐藏 dialog.html -> pageshow index.html -> pageshow dialog.html

    3. 从 dialog.html 到 index.html

      页面隐藏 index.html -> 页面隐藏 dialog.html -> pageshow index.html -> pageshow dialog.html

    解决办法:

    在使用pagebeforehidepagebeforeshowpagehidepageshow 事件时要具体说明

    $(document).on("pageshow", "#pageID", function () {
      /* do something */
    });
    

    【讨论】:

    • 你是个天才!谢谢你。我整晚都在为此绞尽脑汁。
    • 只是给看到此答案的其他人的便条。在上面的答案中,请确保向页面容器 div 添加一个 id,如下所示:
      Same for dialog page
    • @kane,不客气。如果您愿意,我可以详细说明我的答案。写的很匆忙。
    • 我觉得我很好。但是,如果您详细说明,它可能会帮助遇到同样问题的其他人。我相信它会得到更多的支持
    • 我研究了很多,甚至在 jqm 网站上我也找到了这个解决方案。感谢您的回答。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签