Html 在多个html页面之间共享一个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16264253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:58:12  来源:igfitidea点击:

Sharing a variable between multiple html pages

javascripthtml

提问by user2329318

I have a class project to create html page(s) with javascript without using any server side communications, the first is about user input an specially numbers. In the first page an instructor must enter information about his class an its students number, and then when done, he clicks next and a new page opens asking for each student information and grades. But when changing from the first page to the second the variable of the students number becomes undefined. I'm using this part

我有一个类项目,可以在不使用任何服务器端通信的情况下使用 javascript 创建 html 页面,第一个是关于用户输入特殊数字。在第一页中,教师必须输入有关其班级的信息及其学生编号,然后在完成后单击下一步,将打开一个新页面,询问每个学生的信息和成绩。但是当从第一页更改到第二页时,学生编号的变量变为未定义。我正在使用这部分

var  snum;

function savesnum(val){
snum =val;}

And also tried,

也试过了,

var snum;
function savesnum(){
snum = document.getElementById('stunb').value; }

回答by Xotic750

Here is an example of using window.localStorageto pass data between two html pages being served on the same domain. This will not work accross different domains because of the Same-origin policy.

下面是使用window.localStorage在同一域上提供的两个 html 页面之间传递数据的示例。由于同源策略,这不适用于不同的域。

The example consists of two pages hosted on jsfiddle.netbut you could just as easily serve these files from your local file system. Either way there is no server side communication involved in this example.

该示例由托管在jsfiddle.net上的两个页面组成,但您可以同样轻松地从本地文件系统提供这些文件。无论哪种方式,本示例中都没有涉及服务器端通信。

The first page allows the user to enter some text in a textareaelement. There is a save buttonwhich when clicked will fire a click eventthat executes the save handler (the anonymous functionspecified as the second attribute of addEventListener) that gets the user entered text and saves it in localStorage with the key mySharedData

第一个页面允许用户在textarea元素中输入一些文本。有一个保存按钮,单击该按钮时将触发执行保存处理程序(指定为 addEventListener 的第二个属性的匿名函数)单击事件,该处理程序获取用户输入的文本并使用键将其保存在 localStorage 中mySharedData

Page 1 on jsfiddle

jsfiddle 上的第 1 页

HTML

HTML

<textarea id="input"></textarea>
<div>
    <button id="save">Save</button>
</div>

Javascript

Javascript

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */

(function (global) {
    document.getElementById("save").addEventListener("click", function () {
        global.localStorage.setItem("mySharedData", document.getElementById("output").value);
    }, false);
}(window));

The second page recalls the saved text from the key mySharedDatathat is in localStorage and displays it in the textarea

第二页从mySharedDatalocalStorage中的key调出保存的文本并显示在textarea中

Page 2 on jsfiddle

jsfiddle 上的第 2 页

HTML

HTML

<textarea id="output"></textarea>

Javascript

Javascript

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */

(function (global) {
    document.getElementById("output").value = global.localStorage.getItem("mySharedData");
}(window));

Both examples are wrapped in an anonymous closurewhich is executed immediately, and into which we pass the window objectwhich we then reference as the variable named global.

这两个示例都包含在一个匿名包中,该闭包会立即执行,然后我们将window 对象传递给该闭包,然后我们将其作为名为 的变量引用global

Finally, the first line is a comment, but not any old comment; it is an instruction that is used by jslint; a static code analysis tool used in javascript software development for checking if JavaScript source code complies with coding conventionsset out by Douglas Crockford.

最后,第一行是注释,但不是任何旧注释;它是jslint使用的指令;一种用于 javascript 软件开发的静态代码分析工具,用于检查 JavaScript 源代码是否符合Douglas Crockford 制定的编码约定

Alternatives would be to use:

替代方法是使用:

cookies, once again the Same-origin policy would apply.

cookies,再次适用同源政策。

or

或者

URLquery-stringswhich would be part of the address used when taking you to the next page, where it can be read in Javascript to obtain data.

URL查询字符串,它是将您带到下一页时使用的地址的一部分,可以在 Javascript 中读取它以获取数据。

回答by vimist

Look into using cookies:

考虑使用 cookie:

http://www.w3schools.com/js/js_cookies.asp

http://www.w3schools.com/js/js_cookies.asp

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

cookie 是存储在访问者计算机上的变量。每次同一台计算机通过浏览器请求一个页面时,它也会发送 cookie。使用 JavaScript,您可以创建和检索 cookie 值。

function savesnum(val) {
    document.cookie = 'snum:'+val; //Set the cookie
}

function getsnum() {
    var start = document.cookie.indexOf('snum:'); //Get the location of the cookie value
    var stop = document.cookie.indexOf(';'); //Get the end of the cookie value

    return document.cookie.substring(start+5, stop); //Return the value of the cookie (+5 because 'snum:' is 5 chars long)
}

回答by Sean

when you window open a new page or redirect to a new page, you are on a new window object, you are not able to get the "snum" which is defined on the first window object as a global variable.

当您打开一个新页面或重定向到一个新页面时,您在一个新的窗口对象上,您无法获得在第一个窗口对象上定义为全局变量的“snum”。

in this case you can pass the snum as a "get" parameter alone with the url and get the parameter at the new window.

在这种情况下,您可以将 snum 作为“get”参数单独与 url 一起传递,并在新窗口中获取参数。

回答by Ravi Thapliyal

When you write

当你写

var snum;

that just creates a Javascript variable.

这只是创建一个 Javascript 变量。

It doesn't even add snumto the DOM (Document Object Model) of the same page. Which is what you're trying to do (although on a different page) with:

它甚至不会添加snum到同一页面的 DOM(文档对象模型)中。这就是你想要做的(虽然在不同的页面上):

document.getElementById('stunb').value;

You can call getElementById()only to get a DOM node/element like a <p id="mainText">paragraph node. To pass around values from one page to the other you can use:

您只能调用getElementById()以获取 DOM 节点/元素,例如<p id="mainText">段落节点。要将值从一页传递到另一页,您可以使用:

  • Cookies
  • URL parameters (like google.com/search?q=parameter+value)
  • 饼干
  • URL 参数(如 google.com/search?q= parameter+value

There are other methods as well but they would require some server side code.

还有其他方法,但它们需要一些服务器端代码。

In your case you can pass the number of students as follows:

在您的情况下,您可以按如下方式传递学生人数:

<form action="nextPage.html">
    Number of Students: <input type="text" name="snum" />
    <input type="submit" value="Next" />
</form>

On nextPage.html

nextPage.html

<script type="text/script">
<!--
    var snum = location.search.substr(location.search.indexOf("=")+1);
    alert(snum); // assumes snum will be sent as "nextPage.html?snum=10"
//-->
</script>