繁体   English   中英

访问用户从JS中的单独文件获得的变量

[英]Accessing a variable obtained by user from separate file in 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();})

但是,这不起作用。 如果我在函数外部手动定义变量,它将起作用。 我不确定所有操作的时间如何安排,因为在加载文档时未定义我的变量。 我很想知道如何解决这个问题。

这按预期工作。

代替使用全局变量作用域,您可以使用localStorage

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

您可以在第一个文件的localStorage中存储实部和虚部零件号。 您可以在第二个文件中访问它们。

我这是你想做什么?

$("#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可以在全局范围或存储中设置。

暂无
暂无

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

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