【问题标题】:Using Localstorage to store and retrieve javascript variables from one html page to another (DOM)使用 Localstorage 将 javascript 变量从一个 html 页面存储和检索到另一个 (DOM)
【发布时间】:2018-01-05 07:05:35
【问题描述】:

我有一个 html 页面1.html,我想获取一些文本内容并使用 jquery 将其存储到js.js 文件中,以通过 id 获取文本。

此代码仅适用于1.html 页面,我要从中复制的文本是,但不是2.html 文件中。

这是我的代码。请注意,如果我将文本存储在 localstorage setter 第二个参数中,它会起作用。

 $( document ).ready(function() {
         var c1Title= $('#r1c1Title').text();

//changing c1Title to any String content like "test" will work

    localStorage.setItem("t1",c1Title);
        var result = localStorage.getItem("t1");

        $("#title1").html(result);
        alert(result);
    });

这是我正在处理的完整演示 Github

【问题讨论】:

  • 为此使用localstorage
  • @chiragsatapara 怎么样?
  • 使用本地存储
  • @Eternal ,请参考此链接:w3schools.com/html/html5_webstorage.asp。让我给你一个答案示例
  • 您可以通过本地存储来实现,这里您需要确保您在父html页面或父js文件中设置此本地存储值。

标签: javascript php jquery html local-storage


【解决方案1】:

您可以使用上述 cmets 中提到的本地存储。请在下面找到如何用javascript编写。

本地存储的优缺点

优点:

  1. Web 存储可以简单地视为对 cookie 的改进,可提供更大的存储容量。
  2. 5120KB(5MB 相当于 Chrome 上的 250 万个字符)是整个域的默认存储大小。
  3. 与典型的 4KB cookie 相比,这为您提供了更多的工作空间。
  4. 不会将每个 HTTP 请求(HTML、图像、JavaScript、CSS 等)的数据发送回服务器 - 减少客户端和服务器之间的流量。
  5. 存储在 localStorage 中的数据会一直存在,直到被明确删除。所做的更改已保存,可供当前和将来访问该网站的所有用户使用。

缺点:

它适用于同源策略。因此,存储的数据将仅在同一来源上可用。 // 将值存储在本地存储中 localStorage.setItem("c1Title", $('#r1c1Title').text());

// Retrieve value in local storage
localStorage.getItem("c1Title");

你的 html div

<div id="output"></div>

添加 Javascript 代码

$('#output').html(localStorage.getItem("c1Title"));

如果它不起作用,请告诉我

【讨论】:

  • 那么我如何使用它在 html 中打印它?
  • 它在 blog.html 中工作,但我在其他文档中得到空文本,请参阅演示 w3schools.com/code/tryit.asp?filename=FI1YXKN89S0T
  • 我只是检查了您提供的链接,它似乎工作正常。你能告诉我确切的错误吗?
  • 问题不是错误。问题是我看不到除 blog.html 之外的任何其他文件中的文本。我存储在变量 c1Title 中的文本在 blog.html 文件中
  • https://shyamshingadiya.github.io/LocalStorage/1.html本页数据保存在本地存储,在https://shyamshingadiya.github.io/LocalStorage/2.html,https://shyamshingadiya.github.io/LocalStorage/3.html,https://shyamshingadiya.github.io/LocalStorage/4.html你从本地存储获取数据
【解决方案2】:

请尝试使用此代码。最好使用本地存储

这里你需要确保你设置了这个本地存储 父 html 页面或父 js 文件中的值。

创建本地存储

localStorage.setItem("{itemlable}", {itemvalue});

localStorage.setItem("variable1", $('#r1c1Title').text());
localStorage.setItem("variable2", $('#r1c2Title').text());

获取本地存储值

localStorage.getItem("{itemlable}")

alert(localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));

欲了解更多信息,请点击此链接https://www.w3schools.com/html/html5_webstorage.asp

如果您想存储在 div 中,请按照此代码操作。

HTML代码

<div class="div_data"></div>

JS代码:

$(document).ready(function () {
            localStorage.setItem("variable1", "Value 1");
            localStorage.setItem("variable2", "Value 2");
                $(".div_data").html(' First variable ::: '+localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
        });

希望这会有所帮助。

【讨论】:

  • 当我将该代码放入 $( document ).ready(function() { 时它不起作用
  • 确保已包含 jquery。
【解决方案3】:

您需要使用 localStoragecookies

使用本地存储

在第一页,使用以下代码:

localStorage.setItem("variableName", "variableContent")

这为域设置了一个本地存储变量variableName,内容为variableContent您可以将这些名称和值更改为您想要的任何内容,它们只是作为示例使用

在第二页,使用以下代码获取值:

localStorage.getItem("variableName")

这将返回存储在variableName 中的值,即variableContent

注意事项

  • localStorage 中可以存储的数据量有 5MB 的限制。
  • 您可以使用localStorage.removeItem("variableName") 删除项目。
  • 根据您所在的位置,您可能需要查看cookie policy(这会影响在计算机上存储数据的所有形式的网站,而不仅仅是cookie)。 这很重要,否则使用任何这些解决方案都可能是非法的。
  • 如果您只想在用户关闭浏览器之前存储数据,则可以改用 sessionStorage(只需在代码的所有实例中将 localStorage 更改为 sessionStorage
  • 如果您也希望能够在服务器上使用变量值,请改用 cookie - 查看cookies on MDN
  • 有关 localStorage 的更多信息,请查看 this article on MDNthis one on W3Schools

【讨论】:

  • 如果我想将变量内容设置为我存储 elementbyid text() 的变量怎么办?
  • 我使用 localStorage.setItem("t1",c1Title);这适用于 blog.html,但我在其他文件中得到空文本
  • @Eternal 确保您没有在第二页使用localStorage.setItem()(否则会覆盖值),并且您使用的是完全相同相同的键在两个页面上。
  • 在我的问题中查看我的 GitHub 演示
  • 我从 js 获得的内容是不可见的,直到我访问有设置器的页面,我该如何解决这个问题?
【解决方案4】:

创建一个 common.js 文件并修改它并保存。

Session = (function () {
    var instance;
    function init() {
        var sessionIdKey = "UserLoggedIn";
        return {
            // Public methods and variables.
            set: function (sessionData) {
                window.localStorage.setItem(sessionIdKey, JSON.stringify(sessionData));
                return true;
            },
            get: function () {
                var result = null;
                try {
                    result = JSON.parse(window.localStorage.getItem(sessionIdKey));
                } catch (e) { }
                return result;
            }
        };
    };
    return {
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
}());


function isSessionActive() {
    var session = Session.getInstance().get();
    if (session != null) {
        return true;
    }
    else {
        return false;
    }
}


function clearSession() {
    window.localStorage.clear();
    window.localStorage.removeItem("CampolUserLoggedIn");
    window.location.assign("/Account/Login.aspx");
}

像这样插入。

$(function () {
    if (!isSessionActive()) {
        var obj = {};
        obj.ID = 1;
        obj.Name = "Neeraj Pathak";
        obj.OrganizationID = 1;
        obj.Email = "npathak56@gmail.com";
        Session.getInstance().set(obj);
    }

    ///clearSession();
});

这样子

  LoggedinUserDetails = Session.getInstance().get();

【讨论】:

  • 当 OP 可以简单地调用 localStorage.setItem(item, value)localStorage.getItem(item) 时,为什么还需要这么复杂的东西?
猜你喜欢
  • 1970-01-01
  • 2011-04-15
  • 2017-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多