简体   繁体   中英

Accesing variables declared in JAVASCRIPT in a different HTML FILE

I have two files screen.html and db_fun.js.
I have declared a variable at just the beginning as follows:

db_fun.js
var name = "abc";

now i tried to access this variable in the screen.html file as follows

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. Y so?

将此添加到头部

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

That's because you are inserting your JavaScript in the page footer. You have to firstly load your javascript file into your web site (in the head section for example) and then use your variable.

I think that you should move

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

In the head of the page. Ie before 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. Try using jQuery or some other library. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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