[英]Import variables from another JavaScript file
Let's say I want to display all seasons of Family Guy as one number. 假设我想将“全家福”的所有季节显示为一个数字。 (15) But of course there will be more seasons so I would have to change in every file the 15 to 16 and so on.
(15)但是当然会有更多的季节,所以我必须在每个文件中将15改为16,依此类推。 That for I want to create a variable for the value so I just have to change it once for all files.
那是因为我想为该值创建一个变量,所以我只需要为所有文件更改一次即可。
external js.script 外部js.script
var seasons = "15";
document.getElementById('seasons').innerHTML = seasons;
So now I want to include the variable in my HTML files: 所以现在我想在HTML文件中包含变量:
<div id="seasons"></div>
It works but after three variables all other are not displayed. 它可以工作,但是在其他三个变量之后不显示。
Is there a better way to create variables in an external file? 有没有更好的方法可以在外部文件中创建变量?
If you need a group of constants within your application, it's usually a good idea to load them on to a namespace and load that in before any of your other code. 如果您在应用程序中需要一组常量,通常最好将它们加载到名称空间上,然后再将其加载到其他任何代码中。
/* app.js */ // Create the namespace var App = {}; App.Constants = { FAMILY_GUY: 15, SIMPSONS: 28, FUTURAMA: 7 }; /* family-guy.js */ document.getElementById('familyGuy').innerHTML = App.Constants.FAMILY_GUY; /* simpsons.js */ document.getElementById('simpsons').innerHTML = App.Constants.SIMPSONS; /* futurama.js */ document.getElementById('futurama').innerHTML = App.Constants.FUTURAMA;
<div id="familyGuy"></div> <div id="simpsons"></div> <div id="futurama"></div> <!-- Imagine you're loading your files like this <script src="app.js"></script> <script src="family-guy.js"></script> <script src="simpsons.js"></script> <script src="futurama.js"></script> -->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.