jQuery Mobile弹出窗口在.popup('open')时无法打开

5

我想使用jQuery Mobile 1.3.1的弹出框在登录凭证错误时警告用户。我从jquerymobile的文档中开始使用一个基本模板,但是我无法通过$('#popupBasic').popup('open');使其工作。如果我这样使用它;

     <div data-role="page">


        <div data-role="header" data-tap-toggle="false">
        </div><!-- /header -->

        <div data-role="content">

            <a href="#popupBasic" data-rel="popup">Tooltip</a>
            <div data-role="popup" id="popupBasic">I will change this text dynamically if this popup works</div>


        </div><!-- /content -->
    </div><!-- /page -->

当我点击工具提示链接时,它能够正常运行。但在我的情况下,没有任何点击操作,因此我正在尝试以下方法:

                if(retVal){
                    $.mobile.changePage('index');
                }
                else{                    
                    $('#popupBasic').popup();
                    $('#popupBasic').popup("open");
                }

这是我的ajax登录函数回调后,如果没有任何错误,则retVal为true,如果有错误则为false(此时我正在尝试显示弹出窗口)。顺便说一下,我的所有js部分都在。

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

所以我会等到jquerymobile准备好了这个页面。

当我在桌面浏览器上这么做时,链接会更改为

http://localhost/login#&ui-state=dialog

但是弹出窗口没有显示出来。经过一些刷新和缓存后,它开始显示。在iOS上也发生了同样的事情,但在Android上有时会更改链接,有时则不会。

如果有人能帮助我解决这个问题,我将非常感激。 提前致谢。

1个回答

9
这是因为当触发pageinit时,弹出窗口还没有准备好进行操作。您需要使用pageshow来打开弹出窗口。以下是您需要执行的操作:
  • pageinit中进行ajax调用。将数据存储在页面的data属性中。
  • 然后,在pageshow事件中,从数据中取出并按照您想要的方式进行操作,然后打开弹出窗口。
以下是代码示例:
$(document).on({
    "pageinit": function () {
        alert("pageinit");
        //$("#popupBasic").popup('open'); will throw error here because the page is not ready yet
        //simulate ajax call here
        //data recieved from ajax - might be an array, anything
        var a = Math.random();
        //use this to transfer data betwene events
        $(this).data("fromAjax", a);
    },
    //open popup here
    "pageshow": function () {
        alert("pageshow");
        //using stored data in popup
        $("#popupBasic p").html("Random : " + $(this).data("fromAjax"));
        //open popup
        $("#popupBasic").popup('open');
    }
}, "#page1");

这里有一个演示:http://jsfiddle.net/hungerpain/MvwBU/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接