如何在jQM页面之间存储变量?

问题描述 投票:2回答:4

如何在两个jQueryMobile页面之间传递类似用户名的变量?

或与此相关的两个常规页面,将变量设置为全局不起作用,因为在下一个include中,它将变量设置回null。

如何在两个html页面之间为全局变量传递变量?

javascript jquery jquery-mobile
4个回答
6
投票

我通常使用本地存储,您也可以存储对象。例如:

var userInfo = {
            "username": "Bob",
            "roleName": "Admin",
            "image": "img/userPic.jpg",
        };

        //Store the object in local storage
        localStorage.setItem('loggedUser', JSON.stringify(userInfo));

然后在另一页上,您可以简单地做:

var userInfo = JSON.parse(localStorage.getItem("loggedUser"));
var userName = userInfo.username;

1
投票

您可以通过查询字符串或客户端路由使用URL,可以使用localStorage(假设它们在同一域中),也可以使用Cookie。

如果您决定使用客户端路由,则有一个专门用于JQM的插件,它与不同的JQM页面事件相关联

https://github.com/azicchetti/jquerymobile-router


1
投票

只要在两个页面之间的超链接上禁用ajax,就可以在查询字符串中传递它。

<a href="nextPage.php?username=joe" data-ajax="false">Next page</a>

您错过了jQuery移动转换的有益功能,但至少可以成功在页面之间传递变量。

更新:

来自the documentation

页面之间传递参数

jQuery Mobile不支持将查询参数传递给内部/嵌入式页面...

然后文档继续建议两个我没有尝试过的插件。 Page params pluginjquery mobile routing plugin

请务必查看上面链接的文档页面,以获取有关为什么传递参数不起作用的解释,但是如果您在不进行哈希处理的情况下加载页面(通过禁用ajax行为),那么应该没问题-至少在我看来经验。


0
投票

您可以存储变量以供全局使用,就像JQM存储其自己的配置一样。只需在$ mobile的'mobileinit'下创建您自己的javascript对象,并将其用于全局变量:

    <!DOCTYPE html> 
    <html>
    <head>

        ...

        <script> // position before jquery.mobile.js is important for 'mobileinit' to fire
            $( document ).on( "mobileinit", function( event ) {

                //create global variable storage
                $.mobile.YourApplicationNameHere = {};

                //use it like this anywhere in your code:
                $.mobile.YourApplicationNameHere.globalVar1 = 1;
                $.mobile.YourApplicationNameHere.globalVar2 = 2;
                console.log("globalVar1 = " + $.mobile.YourApplicationNameHere.globalVar1);

            });
        </script>

        <script src="jquery/jquery.mobile-1.4.5.min.js"></script>

        ...

    </head>
        ...
    </html>

您可以在任何地方初始化全局变量,但是'mobileinit'是JQM的最早初始化点。

© www.soinside.com 2019 - 2024. All rights reserved.