简体   繁体   English

访问JAVASCRIPT中声明的变量在不同的HTML文件中

[英]Accesing variables declared in JAVASCRIPT in a different HTML FILE

I have two files screen.html and db_fun.js. 我有两个文件screen.html和db_fun.js。
I have declared a variable at just the beginning as follows: 我刚开始就声明了一个变量,如下所示:

db_fun.js db_fun.js
var name = "abc"; var name =“ abc”;

now i tried to access this variable in the screen.html file as follows 现在我尝试按如下方式访问screen.html文件中的此变量

screen.html screen.html

<html> 
 <body> 
   <form name = "screen" action = "db_fun.js"> 
        <p> <script>document.write(name);</script> </p>
   </form>
 </body>  
 <script src="db_fun.js" type="text/javascript" />
</html>

it doesn't print nethn. 它不会打印nethn。 Y so? 是吗

将此添加到头部

<script type="text/javascript" src="db_fun.js"></script>

That's because you are inserting your JavaScript in the page footer. 那是因为您要在页面页脚中插入JavaScript。 You have to firstly load your javascript file into your web site (in the head section for example) and then use your variable. 您必须首先将javascript文件加载到您的网站中(例如,在头部),然后使用变量。

I think that you should move 我认为你应该搬家

<script src="db_fun.js" type="text/javascript" />

In the head of the page. 在页面的顶部。 Ie before document.write. 即在document.write之前。 Because in the moment where you are trying to print 'name', the variable is still not created. 因为在您尝试打印“名称”的那一刻,仍未创建该变量。 Also I think that it is not a very good practice to use document.write to add content to your page. 另外,我认为使用document.write将内容添加到页面不是一个很好的做法。 Try using jQuery or some other library. 尝试使用jQuery或其他库。 For example: 例如:

$(document).ready(function() { 
   $("p").html(name);
});

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

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