Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript在HTML之间交换变量?_Javascript_Html_Variables - Fatal编程技术网

如何使用JavaScript在HTML之间交换变量?

如何使用JavaScript在HTML之间交换变量?,javascript,html,variables,Javascript,Html,Variables,我有2个html页面和javascript。我希望第2页中的x变量显示在第1页上 页面2.html var x =1; 页面1.html <input type="Button" id="text2" value="click" onclick=show()/> 您可以使用between在两个HTML页面之间交换变量 饼干 质询 例如: <a href='page1.html?x=1'>First link</a> <a href='page2.

我有2个html页面和javascript。我希望第2页中的x变量显示在第1页上

页面2.html

var x =1;
页面1.html

<input type="Button" id="text2" value="click" onclick=show()/>

您可以使用between在两个HTML页面之间交换变量

  • 饼干
  • 质询
例如:

<a href='page1.html?x=1'>First link</a>
<a href='page2.html?y=2'>Second link</a>

同时检查您可以在
Data.js
文件中编写这样的代码

localStorage.setItem("score", x); //x-variable,setting values in localstorage;

var foo = localStorage.getItem("score"); //Get values from localstorage.

您可以为此使用cookies:

document.cookie="score="+x; // this will create the cookie

// Other HTML page, you will use getCookie("score")
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) != -1) return c.substring(name.length,c.length);
    }
    return "";
}

var score = getCookie("score");
console.log(score);
document.cookie=“score=“+x;”/这将创建cookie
//其他HTML页面,您将使用getCookie(“分数”)
函数getCookie(cname){
变量名称=cname+“=”;
var ca=document.cookie.split(“;”);

对于(var i=0;iIs)在同一网站上发生这种情况?如果从第1页转到第2页,则不应丢失“x”变量的值。请尝试使用Cookie或localstorage(仅限HTML 5)页面是同时显示的,还是按顺序显示的?如果按顺序从第1页转到第2页时只使用URL参数?页面是同时显示的,我不想立即发送变量并更改到其他页面。
localStorage.setItem("score", x); //x-variable,setting values in localstorage;

var foo = localStorage.getItem("score"); //Get values from localstorage.
document.cookie="score="+x; // this will create the cookie

// Other HTML page, you will use getCookie("score")
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) != -1) return c.substring(name.length,c.length);
    }
    return "";
}

var score = getCookie("score");
console.log(score);