JS

2016-07-06 8 views
0

初心者の質問に別のファイルからのユーザーによって得られた変数へのアクセス:私は、ユーザーからの架空の番号を取得アプリを作成して、複素平面にプロットしたいと思いますJS

を。私は後で別のものを追加したいので、HTMLファイルで接続された別々のファイルにコードを保存します。最初のファイルで

、私は、ユーザーからの実数と複雑な部分を取得:しかし、これは動作しません

$(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番目のファイルに使用

$(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:") 
});}) 

を。関数の外で変数を手動で定義すると動作します。ドキュメントの読み込み時に変数が定義されていないため、すべての操作がどのようにタイミングがとられているかはわかりません。私はこの問題を解決する方法を知りたいです。

+2

[JavaScriptの変数の範囲は何ですか?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Turnip

+0

モジュール搭載システム。 – gcampbell

+0

[Javascript外部の.jsファイルで定義された変数へのアクセス]の可能な複製(http://stackoverflow.com/questions/10864732/javascript-accessing-variables-defined-in-external-js-files) –

答えて

0

期待どおりに動作します。代わりにあなたがあなたの最初のファイルでのlocalStorageで実際の虚部の番号を格納できるのlocalStorage

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

を使用することができ、グローバル変数のスコープを使用して

。そして、2番目のファイルでそれらにアクセスできます。

+0

ありがとうございました。私は簡単なソリューションなので、このソリューションを使用しました。 – Ardweaden

0

私はあなたの何をしようとしていますか?あなたのやって...
REALPARTとimagPartがグローバルスコープやストレージで設定することができるものの

$("#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/ または一部。

+0

はい、違いは、描画用のコードが別のファイルにある点です。 – Ardweaden