[英]Retrieving variable values from Javascript file rather than HTML/CSS
[英]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 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.