简体   繁体   中英

how to pass a variable from html file to javascript file

I need to pass a variable from page1.html file to page2.js . Must include pure javascript code (without tags like <script> ).

page1.html :

<script type="text/javascript">
  var age = 23;
</script>
<html>
  <!-- some code I need -->
</html>

page2.js :

print(age);
<script type="text/javascript">
  var age = 23;
</script>
<script type="text/javascript" src="your-second_script name"></script>
<html>
  <!-- some code I need -->
</html>

It should work Or else load both javascript externally and load first script which have that variable and then second script which is using that variable

You can add this code in your page1.html :

<input value="23" type="text" hidden="hidden" id="myVariable" />

and get your variable value in page2.js by this code:

alert(document.getElementById('myVariable').value)

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