简体   繁体   English

使用Localstorage存储和检索从一个html页面到另一个html页面的javascript变量(DOM)

[英]Using Localstorage to store and retrieve javascript variables from one html page to another (DOM)

I have one html page 1.html and i want to get some text content and store it to a js.js file using jquery to get the text by id. 我有一个html页面1.html ,我想得到一些文本内容,并使用jquery将其存储到js.js文件,以获取id的文本。

This code only works in 1.html page, where the text I want to copy from is but not in 2.html file. 此代码仅适用于1.html页面, 其中我要复制的文本 不在 2.html文件中。

Here is my code. 这是我的代码。 Note that it works if I store text inside localstorage setter second parameter. 请注意,如果我将文本存储在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);
    });

Here is the complete demo I am working on Github : 这是我在Github上工作的完整演示:

You need to use either localStorage or cookies . 您需要使用localStoragecookie

With localStorage 随着localStorage

On the first page, use the following code: 在第一页上,使用以下代码:

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

That sets a localStorage variable of variableName for the domain, with the content variableContent . 这集的localStorage的变量variableName域,与内容variableContent You can change these names and values to whatever you want, they are just used as an example 您可以将这些名称和值更改为您想要的任何名称和值,它们仅用作示例

On the second page, get the value using the following code: 在第二页上,使用以下代码获取值:

localStorage.getItem("variableName")

That will return the value stored in variableName , which is variableContent . 这将返回存储在variableName的值,即variableContent

Notes 笔记

  • There is a 5MB limit on the amount of data you can store in localStorage. 您可以在localStorage中存储的数据量限制为5MB。
  • You can remove items using localStorage.removeItem("variableName") . 您可以使用localStorage.removeItem("variableName")删除项目。
  • Depending on where you are, you may need to take a look at the cookie policy (this effects all forms of websites storing data on a computer, not just cookies). 根据您所处的位置,您可能需要查看Cookie政策 (这会影响在计算机上存储数据的所有形式的网站,而不仅仅是Cookie)。 This is important, as otherwise using any of these solutions may be illegal. 这很重要,否则使用任何这些解决方案可能都是非法的。
  • If you only want to store data until the user closes their browser, you can use sessionStorage instead (just change localStorage to sessionStorage in all instances of your code) 如果您只想在用户关闭浏览器之前存储数据,则可以使用sessionStorage(只需在所有代码实例中将localStorage更改为sessionStorage
  • If you want to be able to use the variable value on the server as well, use cookies instead - check out cookies on MDN 如果您希望能够在服务器上使用变量值,请使用cookie - 检查MDN上的cookie
  • For more information on localStorage, check out this article on MDN , or this one on W3Schools 有关localStorage的更多信息,请查看有关MDN的这篇文章 ,或W3Schools 上的这篇文章

Please try to use this code. 请尝试使用此代码。 It's better to use local storage . 最好使用本地存储

Here you need to make sure that you are setting this local storage value in parent html page or parent js file. 在这里,您需要确保在父html页面或父js文件中设置此本地存储值。

create local storage 创建本地存储

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

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

Get local storage value 获取本地存储价值

localStorage.getItem("{itemlable}") localStorage.getItem( “{itemlable}”)

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

For more information follow this link https://www.w3schools.com/html/html5_webstorage.asp 有关更多信息,请访问此链接https://www.w3schools.com/html/html5_webstorage.asp

If you wanted to store in div then follow this code. 如果您想存储在div中,请遵循此代码。

Html Code Html代码

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

Js code: 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"));
        });

Hope this helps. 希望这可以帮助。

You can use local storage as mentioned in above comments. 您可以使用上述注释中提到的本地存储。 Please find below how to write in javascript. 请在下面找到如何用javascript编写。

Local Storage Pros and Cons 本地存储优点和缺点

Pros: 优点:

  1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. 可以简单地将Web存储视为对cookie的改进,从而提供更大的存储容量。
  2. 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. 5120KB(5MB,相当于Chrome上的250万个字符)是整个域的默认存储大小。
  3. This gives you considerably more space to work with than a typical 4KB cookie. 与典型的4KB cookie相比,这为您提供了更多的工作空间。
  4. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server. 对于每个HTTP请求(HTML,图像,JavaScript,CSS等),数据不会发送回服务器 - 减少客户端和服务器之间的流量。
  5. The data stored in localStorage persists until explicitly deleted. 存储在localStorage中的数据将一直存在,直到被明确删除。 Changes made are saved and available for all current and future visits to the site. 所做的更改将保存,并可用于该网站的所有当前和未来访问。

Cons: 缺点:

It works on same-origin policy. 它适用于同源策略。 So, data stored will only be available on the same origin. 因此,存储的数据只能在同一个来源上使用。 // Store value in local storage localStorage.setItem("c1Title", $('#r1c1Title').text()); //将值存储在本地存储localStorage.setItem(“c1Title”,$('#r1c1Title')。text());

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

Your html div 你的html div

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

Add Javascript Code 添加Javascript代码

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

Let me know if it not works 如果它不起作用,请告诉我

Create a common.js file and modified this and save. 创建一个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");
}

Insert like this. 像这样插入。

$(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();
});

get like this way 得到这样的方式

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用本地存储将 html 页面中的 javascript 变量传递到另一个页面 - Pass javascript variables from a html page to another using local storage 如何在此 HTML 页面中存储数据并使用 JavaScript 在另一个页面中检索它 - How do I store data in this HTML page and retrieve it in another using JavaScript 如何使用Ajax从一个HTML页面中使用数据来检索要在另一HTML页面上使用的数据 - How to use data from one HTML page to retrieve data to be used on another HTML page using ajax 如何使用 JavaScript 和 HTML 使用 localStorage 存储数据? - How to store data with localStorage using JavaScript and HTML? 如何使用javascript将数据从一个html页面传输到另一页面 - how to transfer data from one html page to another using javascript 使用 javascript 将数据从一个 html 页面转移到另一个页面 - Carrying over data from one html page to another using javascript 从localStorage存储和检索Set - Store and retrieve Set from localStorage 如何在一个HTML页面上使用JavaScript和DOM从外部链接到另一个HTML页面 - How to use JavaScript & DOM on one html page to externally link to another html page 如何使用javascript将值从一个html页面传递到另一个html页面 - How can I pass values from one html page to another html page using javascript 使用 JavaScript 从一个 HTML 页面和 output 到另一个 Z4C4AD5FCA2E7A18AA74DBB1CED003 页面获取输入 - Using JavaScript to take input from one HTML page and output to another HTML page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM