在新窗中访问JavaScript变量

access JavaScript variable in new window

本文关键字:变量 JavaScript 访问 新窗中      更新时间:2023-09-26

这是我的第一次JavaScript尝试,所以如果事情有点混乱,我很抱歉。

我有两个html页面(Certificate1.html和Certificate2.html)。我要做的是提示用户在Certificate1.html上输入他/她的名字,然后将该信息传递给Certificate2.html。此时,用户的姓名将显示在他可以打印的证书中。

两个html页面引用同一个JavaScript文件(Certificate1.js)。第一页调用passName():

function passName() {
    FirstN = document.frmUserName.inFirstN.value;
    LastN = document.frmUserName.inLastN.value;
   // alert(FirstN); // good
   // alert(LastN); // good
    var Cert = window.open("Certificate2.html");
    Cert.FirstN = FirstN;
    Cert.LastN = LastN;
    //alert(Cert.FirstN); //good
    //alert(Cert.LastN); //good
}

这似乎工作正常。我卡住的地方是Certificate2.html调用的函数placeName()。我让它触发onLoad,我知道它正在正确地访问函数(我只是在那里贴了一个警告,它出现了)。我不知道如何访问我在passName()中传递给Cert的FirstN和LastN变量。我试过了。第一个n,但我得到"未定义"我如何访问我(认为我)传递的FirstN和LastN变量?

谢谢!克里斯汀

更新:

了! !

我不需要通过窗口访问它。我已经把变量传递给了窗口,所以我可以直接访问它们。

function placeName() {
    //alert(FirstN);
    document.getElementById("pUserName").innerHTML = FirstN + " " + LastN;
}

谢谢你们了! !克里斯汀

HTML LocalStorage (HTML5)http://diveintohtml5.info/storage.html

第一个文件

:

localStorage.setItem("FirstN", document.frmUserName.inFirstN.value);
第二行

var FirstN = localStorage.getItem("FirstN");

或者直接设置Cookies…

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

但我认为这应该使用PHP或至少不是JS

在新窗口中使用window.opener对象

window.opener.FirstN

W3Schools例子

我可以传递一个JavaScript变量到另一个浏览器窗口吗?

下面的代码适用于我的设置:

first.html

<html>
 <script>
   var Var1 = "MyStringVar";
   var Var2 = 123;
   var win = window.open("second.html");
 </script>
</html>

second.html

<html>
 <script>
   alert(window.opener.Var1);
   alert(window.opener.Var2);
 </script>
</html>

UPDATE:

了! !

我不需要通过窗口访问它。我已经把变量传递给了窗口,所以我可以直接访问它们。

function placeName() {
    //alert(FirstN);
    document.getElementById("pUserName").innerHTML = FirstN + " " + LastN;
}

谢谢你们了! !克里斯汀

第一个窗口文件:

窗口。

第二个窗口文件:

window.opener.yourVariable

description:声明yourVariable为全局变量,并将其绑定到父窗口。如果从父窗口打开新窗口,则可以从'window.opener'访问数据。由于yourVariable被声明为全局变量,父窗口的值可以通过使用'window.opener.yourVariable'

从子窗口访问。