简体   繁体   English

如何访问其他javascript var

[英]How can I access other javascript var

I have an app and different javascript files. 我有一个应用程序和不同的javascript文件。

From HTML I want to be able to access var from those different javascript files. 从HTML,我希望能够从那些不同的javascript文件访问var。

How should I do that?? 我应该怎么做?

EXAMPLE JAVASCRIPT: 示例JAVASCRIPT:

var one = {
  att1: 'myString1',
  att2: 'myString2'
  ...
};

var two = {
  att1: 'myString3',
  att2: 'myString4',
  ...
};

EXAMPLE HTML: 示例HTML:

<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" charset="utf-8" src="js/idiomas.js"></script>
<script type="text/javascript" src="jqueryMobile/jquery-1.11.0.js"/></script>
......

EDIT: 编辑:

Sorry, missed one part. 抱歉,错过了一部分。 This is where I try to access the data: 这是我尝试访问数据的地方:

<script type="text/javascript">
  var atrib1 = document.getElementById("idAtr1");
  var atrib4 = document.getElementById("idAtr4");
  .....
  atrib1.innerHTML = one.att1;
  atrib4.innerHTML = two.att2;
  ....
</script>

You have to maintain hierarchy. 您必须维护层次结构。 For example. 例如。

<script src="file1.js"></script>  
<script src="file2.js"></script>

then you can able to access file1.js variables on file2.js but can't access file2.js on file1.js. 那么您可以访问file2.js上的file1.js变量,但不能访问file1.js上的file2.js Rules is javascript read files sequentially. 规则是javascript按顺序读取文件。 So, if you try to access function/variables/object before they are available will get error. 因此,如果您尝试在功能可用之前访问函数/变量/对象,则会出错。

Otherwise, If you want to access both files variable, you may try followings: 否则,如果要访问两个文件变量,则可以尝试以下操作:

<script src="file1.js"></script>  
<script src="file2.js"></script>
<!-- import your js files that contain those variable -->
<script>
  var atrib1 = document.getElementById("idAtr1");
  var atrib4 = document.getElementById("idAtr4");
  //import your js files above and then call it.
  atrib1.innerHTML = one.att1;
  atrib4.innerHTML = two.att2;

</script>

If you have still doubt. 如果您仍有疑问。 Mention that on comment. 提及评论。 We'll try to help :) 我们将尽力帮助:)

Simply add those js files in your HTML, and access those variables normally. 只需在HTML中添加这些js文件,然后正常访问这些变量即可。

<!-- Your script containing the variables -->
<script type="text/javascript" charset="utf-8" src="js/idiomas.js"></script>

...

<script type="text/javascript">
    console.log(one);  // Access the variable normally
</script>

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

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