简体   繁体   English

访问另一个javascript文件/Html文件中的Javascript变量值

[英]Accessing Javascript variable Value in another javascript file / Html file

Say I have a js file and a html file:假设我有一个 js 文件和一个 html 文件:

jScript1.js jScript1.js

var a = 0.05 ;
var var1 = a;
function myFunc1(){
    console.log("original"+ a);
    a = a*5 ;
    console.log("processed a"+ a) ;
    var1 = a;
}

index.html索引.html

<body>
<script src="jScript1.js">myFunc1();</script>

<script>

console.log("display"+ a);
</script>

</body>

I am able to access var1 in js file but when I use it, I get the initialization value [in this case 0.05] and not the processed value which is stored in var1 after calling myFunc() in the script tag with js file as script resource我能够访问 js 文件中的 var1,但是当我使用它时,我得到了初始化值 [在这种情况下为 0.05],而不是在使用 js 文件作为脚本调用脚本标记中的 myFunc() 后存储在 var1 中的处理值资源

How to get the final value of var1 in the html file after the processing that is happening inside myFunc()?在myFunc() 内部进行处理后,如何获取html 文件中var1 的最终值?

Relevant excerpts from the specification (I took them from https://dev.w3.org/html5/spec-preview/the-script-element.html in particular):规范中的相关摘录(我特别是从https://dev.w3.org/html5/spec-preview/the-script-element.html 获取的):

When used to include dynamic scripts, the scripts may either be embedded inline or may be imported from an external file using the src attribute.当用于包含动态脚本时,脚本可以嵌入内联,也可以使用 src 属性从外部文件导入。
[...] [...]
(Step 15.) (第 15 步。)
[...] [...]
If the element has a src attribute如果元素有一个 src 属性
The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.在准备脚本算法开始时,必须将该元素添加到脚本元素的文档中将尽快执行的脚本集。 [...] [...]

Otherwise除此以外
The user agent must immediately execute the script block, even if other scripts are already executing.用户代理必须立即执行脚本块,即使其他脚本已经在执行。

I am not sure how it has gone unnoticed, but that myFunc1();我不确定它是如何被忽视的,但是myFunc1(); call simply does not get executed, and its logs do not appear at all. call 根本不会被执行,它的日志根本不会出现。
If you try如果你试试

<body>
  <script src="jScript1.js"></script>

  <script>
    console.log("display1 " + a);
    myFunc1();
    console.log("display2 " + a);
  </script>
</body>

instead, that will work.相反,这会起作用。

(While the notation 'dynamic script' may seem a bit confusing, the alternative is 'data block') (虽然符号“动态脚本”可能看起来有点混乱,但替代方法是“数据块”)

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

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