2016-07-06 50 views
0

初學者問題而獲得的變量:訪問由用戶從單獨的文件中的JS

我想創建一個應用程序,其中我從用戶獲取一個虛數,並將其繪製到複平面。由於我希望稍後添加其他內容,因此我將代碼保存在單獨的文件中,並以HTML文件形式連接。

在第一個文件,我得到了真正的和複雜的部分從用戶:

$(document).ready(function() { 
$("#button-number").click(function() { 
    var realPart = prompt("Please, enter the real Part of the number:") 
    var imagPart = prompt("Please, enter the imaginary Part of the number:") 
});}) 

,我在第二個文件中使用:

$(document).ready(function() { 
var c = document.getElementById("ComplexPlane"); 
var number = c.getContext("2d"); 
number.beginPath(); 
number.arc(500+50*realPart,300-50*imagPart,10,0,2*Math.PI); 
number.stroke(); 
number.fill();}) 

但是,這是行不通的。如果我在函數外部手動定義變量,它將起作用。我不完全確定所有的操作是如何計時的,因爲我的變量在文檔加載時沒有定義。我很想知道如何解決這個問題。

+2

可能重複的[JavaScript中的變量範圍是什麼?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Turnip

+0

嘗試使用模塊加載系統。 – gcampbell

+0

[Javascript外部.js文件中定義的Javascript訪問變量]可能重複(http://stackoverflow.com/questions/10864732/javascript-accessing-variables-defined-in-external-js-files) –

回答

0

這按預期工作。

而不是使用全局變量的作用域,你可以使用localStorage的

http://www.w3schools.com/html/html5_webstorage.asp

你可以存儲在localStorage的實虛部數字在你的第一個文件。你可以在第二個文件中訪問它們。

+0

非常感謝。我現在使用這個解決方案,因爲它更容易。 – Ardweaden

0

我這是你想做什麼?

$("#button-number").click(function() { 
    var realPart = prompt("Please, enter the real Part of the number:") 
    var imagPart = prompt("Please, enter the imaginary Part of the number:") 
    if (realPart != null && imagPart != null) { 
    var c = document.getElementById("ComplexPlane"); 
    var number = c.getContext("2d"); 
    number.beginPath(); 
    number.arc(parseInt(realPart),parseInt(imagPart),10,0,2*Math.PI); 
    number.stroke(); 
    } 
}); 

https://jsfiddle.net/LeroyRon/93jvtrae/ 或你做什麼...部分
realPart和imagPart可以在全球範圍內或存儲設置。

+0

是的,但不同之處在於繪圖代碼位於單獨的文件中。 – Ardweaden