简体   繁体   English

如何使每个HTML页面的全局变量都具有不同的值?

[英]How to make a global variable have a different value with each html page?

I am creating a game (like 4 pics 1 word) and it involves having an answer variable. 我正在创建一个游戏(例如4个图片1个单词),并且涉及到一个answer变量。 There will be a button that onclick will run a function that checks the user's answer if it matches the value of this variable. 将有一个按钮,onclick将运行一个函数,该函数检查用户的答案是否与该变量的值匹配。 There will be one puzzle per page and each puzzle/page will have a different value for answer variable. 每页将有一个拼图,每个拼图/页面的答案变量将具有不同的值。 This variable must have its value set when the page loads. 页面加载时必须设置此变量的值。 I looked it up and I don't see anything that would help me and I have no idea how I would do this. 我抬起头,看不到有什么对我有帮助的,我也不知道该怎么做。 Thanks in advance. 提前致谢。

You might need either localStorage or use Cookies for this case. 在这种情况下,您可能需要localStorage或使用Cookies If you are targeting modern browsers, you are free to use localStorage , which is a concept of HTML5. 如果您以现代浏览器为目标,则可以随意使用localStorage ,这是HTML5的概念。

When you are using the click event, use this: 使用click事件时,请使用以下命令:

localStorage.setItem('scores', [scores-array]);

And then when you are loading the page, try this: 然后,当您加载页面时,请尝试以下操作:

localStorage.getItem('scores');

To learn more about localStorage , use this: 要了解有关localStorage更多信息,请使用以下命令:

The other option of Cookies , depends on your browser's privacy settings. Cookies的另一个选项取决于您浏览器的隐私设置。 Many browsers (not many) would probably disable cookies, but you can use it as an alternate. 许多浏览器(不是很多)可能会禁用cookie,但是您可以将其用作备用浏览器。 You have limited data type storage (only strings), which can be initiated using: 您的数据类型存储空间有限(仅字符串),可以使用以下命令启动:

document.cookie="scores=" + score_data;

And retrieving them using: 并使用以下方法检索它们:

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}
getCookie(scores);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM