简体   繁体   English

访问在 html 中的单独 JavaScript 文件上声明的变量

[英]access a variable declared on a separate JavaScript file in html

I have 2 files the first one is an HTML file the other one is a javascript file.我有 2 个文件,第一个是 HTML 文件,另一个是 javascript 文件。 What I was trying to do was define a variable on the javascript file and access it on the Html side.我试图做的是在 javascript 文件上定义一个变量并在 Html 端访问它。 Is it possible?可能吗? A rough code is attached below but it doesn't work I get favColor is not defined error.下面附上了一个粗略的代码,但它不起作用我得到 favColor 未定义错误。 thanks in advance.提前致谢。

JS Side JS端

const favColor = "red"

Html side Html侧

<script src="pathtojsfile"></script>

<p id="insertHere"></p>

<script>
document.getElementById("insertHere").innerHTML = favColor
</script>

As the code is written in your example it should work fine.由于代码是在您的示例中编写的,因此它应该可以正常工作。 Just like my example here:就像我在这里的例子:

 <script> const favColor = "red"; </script> <p id="insertHere"></p> <script> document.getElementById("insertHere").innerHTML = favColor; </script>

But there can be a number of issues if the code is not like this.但是如果代码不是这样,可能会出现很多问题。 But the JavaScript code could just go in the same file.但是 JavaScript 代码只能 go 在同一个文件中。 Try to separate the html from the JS like this (the code in the script element could be moved to it's own file):尝试像这样将 html 与 JS 分开(脚本元素中的代码可以移动到它自己的文件中):

 <html> <head> <script> const favColor = "red"; document.addEventListener('DOMContentLoaded', e => { document.getElementById("insertHere").innerHTML = favColor; }); </script> </head> <body> <p id="insertHere"></p> </body> </html>

Here I'm also adding the eventlistener for DOMContentLoaded, so that I'm sure that the document is loded into the DOM.在这里,我还为 DOMContentLoaded 添加了事件侦听器,以便确定文档已加载到 DOM 中。

It is widely considered bad practice to work with global variables.使用全局变量被广泛认为是不好的做法。 To avoid it, you can make use of ECMAScript Modules, introduced back in 2015 with ES6/ES2015.为避免这种情况,您可以使用 ECMAScript 模块,该模块于 2015 年随 ES6/ES2015 引入。

This allows your first Javascript, let's name it colors.module.js to export the variable:这允许您的第一个 Javascript,我们将其命名为colors.module.jsexport变量:

export const favColor = 'red';

Then, in your script that needs to access this variable, you import it:然后,在需要访问此变量的脚本中,将其导入:

import { favColor } from '/path/to/js/modules/colors.module.js';

For that to work, you need your importing script to have type=module attribute, and the import must be done on top of your Javascript.为此,您需要导入脚本具有type=module属性,并且import必须在 Javascript 之上完成。 The script you import from does not need to be included in the page .从中导入的脚本不需要包含在页面中

Here's some helpful links to get you started with modules:以下是一些有用的链接,可帮助您开始使用模块:

I've set up a tiny github repo demonstrating this very basic usage of an ES module .我建立了一个微型 github 存储库,展示了 ES 模块的这个非常基本的用法

If modules are not an option, eg because you must support IE 11, or your build stack doesn't support modules, here's an alternative pattern that works with a single namespace object you attach to the global object window :如果模块不是一个选项,例如因为您必须支持 IE 11,或者您的构建堆栈不支持模块,那么这里有一个替代模式,它适用于您附加到全局 object window

// colors.module.js
window.projectNamespace = window.projectNamespace || {};
projectNamespace.colors = window.projectNamespace.colors || {};
projectNamespace.colors.favColor = 'red';

and in your page you access it from that name space:并在您的页面中从该名称空间访问它:

document.getElementById("insertHere").innerHTML = window.projectNamespace.colors.favColor;

This way you have a single location to put all your globally accessible variables.这样,您就可以在一个位置放置所有全局可访问的变量。

Where your variable is declared is not the problem per se , but rather the loading order of scripts.声明变量的位置本身不是问题,而是脚本的加载顺序。 If you want to make sure external scripts are loaded before you execute yours, you can use the load event of window object.如果要确保在执行之前加载外部脚本,可以使用window object 的load事件。 It will wait until all resources on your page are loaded though (images, css, etc.)...它会等到页面上的所有资源都加载完毕(图像、css 等)...

 const myvar = "Hey I'm loaded";
 <.DOCTYPE html> <html lang="en"> <head> <title>Document</title> <script> //console;log(myvar). //<- fails window,addEventListener('load'. e => { document.querySelector('#insertHere');innerHTML = myvar; }); </script> </head> <body> <p id="insertHere"></p> </body> </html>

Or you can put all your code in js files, and they will be invoked in the order they are declared.或者你可以把你所有的代码放在js文件中,它们会按照声明的顺序被调用。

Edit Given objections and more questions popping in the comments, I'll add this.编辑鉴于评论中出现的反对意见和更多问题,我将添加此内容。 The best and cleanest way to achieve this remains to put your code in a .js file of its own and put all your <script> tags inside <head> , with yours last, as it relies on others to run.实现这一点的最佳和最简洁的方法仍然是将您的代码放在自己的.js文件中,并将所有<script>标记放在<head>中,最后是您的,因为它依赖于其他人来运行。

Then you can either add the attribute defer to your <script> or have everything wrapped in an event handler for DOMContentLoaded so that it gets run after the DOM is fully loaded.然后,您可以将属性defer添加到<script>或将所有内容包装在DOMContentLoaded的事件处理程序中,以便在 DOM 完全加载运行。

<!DOCTYPE html>
<html lang="en">
  <head>
      <title>Document</title>
      <script src='other1.js'></script> <!-- let's say this one declares myvar -->
      <script src='other2.js'></script>
      <script src='other3.js'></script>
      <script src='myscript.js'></script>
  </head>
  <body>
    <p id="insertHere"></p>
  </body>
</html>

myscript.js myscript.js

window.addEventListener('DOMContentLoaded', e => {
    document.querySelector('#insertHere').innerHTML = myvar;
});

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

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