繁体   English   中英

从Java脚本文件中获取变量

[英]Retrieving Variable From A Javascript File

我的问题是如何在两个不同的javascript文件之间共享变量。 我正在创建一个将值传输到另一个页面的表单,该页面将对该变量发出警报。 我有2个html文件(index.html和form.html)以及2个javascript文件(form.js和index.js)。 因此,基本上我想将变量theNick从form.js共享到index.js,以使用alert()显示它。 如果无法做到这一点,还有其他方法吗?

form.html:

<input type="text" id="Nick" placeholder="Nickname">
<a id="btn" onclick="submit()" href="index.html.">Submit</a>

form.js:

function submit(){
     var theNick = document.getElementById("Nick").value; //retrieves theNick from your input
     ???

}

index.html:

<button onclick="callNick()">Click Me to view your Nickname.</button>  

index.js:

function callNick(){
    ???????
    alert(theNick); //I want to get access to this variable from form.js
}   

通过使用var关键字,您所做的恰恰相反。 如果要共享某些内容,最简单的方法是将变量绑定到window对象,如下所示: window.theNick = ...并像alert(window.theNick)一样使用它。

您可以在函数外部声明变量

var theNick; // you could omit this entirely since it will be declared in 
             // global scope implicitly when you try to assign it in the function
function submit(){
    theNick = document.getElementById("Nick").value; //retrieves theNick from your input
}

javascript不在乎要声明哪些文件,而是在哪个范围内声明。

通过将变量放在全局范围内,您将可以在任何地方访问它。

全局变量不是最佳的编码策略,但这可以帮助您理解

这是可能的。

首先,您需要确保HTML加载了两个JavaScript文件。 它们之间确实没有相互导入的方法,因此HTML必须加载两个脚本。

其次,您需要修改函数submit以使用全局变量。 全局变量最初是在函数范围之外定义的。 函数callNick已经在寻找全局变量。

但是,由于在函数范围内使用了关键字var ,因此submit函数正在定义自己的局部变量。 像这样更改它:

// Set global variable 
var theNick;

function submit(){
      // Use global variable 
      theNick = document.getElementById("Nick").value; //retrieves theNick from your input
      ???

}

有关更多信息,请参见本文。 http://www.w3schools.com/js/js_scope.asp

您可以使用?yourVar= GET标记将变量传递到url中:

form.js

function submit(e){
     var theNick = document.getElementById("Nick").value; //retrieves theNick
     e.target.href+='?n='+theNick; // set the href of your anchor with your variable
}

form.html

<input type="text" id="Nick" placeholder="Nickname">
<!-- We pass the event object into our function as a parameter -->
<a id="btn" onclick="submit(event)" href="index.html">Submit</a>

index.js

function callNick(){
    // get the variable from the current location
    var theNick = window.location.href.split('?n=')[1];
    alert(theNick);
}

index.html

<button onclick="callNick()">Click Me to view your Nickname.</button> 

▶︎ 柱塞 ,其中“形式”已更改为“索引”,“索引”已更改为“结果”。

注意 :
要传递多个变量,可以使用&分隔符,然后按照本CSS技巧文章中的方法使用window.location.search属性。
▶︎ 多个var塞

似乎您需要将变量存储在window对象的本地存储对象中,这样您就可以在第一页上设置其值,然后在第二页上对其进行检索。

第1页

window.localStorage.setItem("yourVariable", "yourValue");

第2页

var myVar = localStorage.getItem("yourVariable");

只有一个'caveat':这是html5功能,因此具有局限性,请查看此链接以获取更多信息。

暂无
暂无

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

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