简体   繁体   English

从 index.html 访问 javascript 模块类/对象

[英]Access to javascript module Class/object from index.html

I defined Class in my javascript file...I imported that file into html page:我在我的 javascript 文件中定义了 Class ...我将该文件导入 html 页面:

<script type="module" src="./js/controller.js"></script>

How can I now acces to classes inside of that js file?我现在如何访问该 js 文件中的类? I want to have something like this (in my html file):我想要这样的东西(在我的 html 文件中):

<script>
  let app = null;
  document.addEventListener('DOMContentLoaded', function () {
    //Init app on DOM load
    app = new MyApp();
  });
</script>

But it doesn't work (I get Uncaught ReferenceError: MyApp is not defined)...If I include this DOMContentLoaded listener into end of my controller.js file, It works.但它不起作用(我得到 Uncaught ReferenceError: MyApp is not defined)...如果我将此 DOMContentLoaded 侦听器包含在 controller.js 文件的末尾,它会起作用。 But I lost reference to app variable this way (which I don't want)... Is there way to have reference to something defined in modules?但是我以这种方式失去了对 app 变量的引用(我不想要)......有没有办法引用模块中定义的东西?

Most important reason why I want to have that reference is ability to access to my app object from google chrome console...我想要获得该参考的最重要原因是能够从谷歌浏览器控制台访问我的应用程序 object ...

Thanks!谢谢!

You can access your class in js file from html in the following way-您可以通过以下方式从 html 访问 js 文件中的 class -

My Home.html file:我的主页.html 文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <script type="module">
        import { Car } from "./main.js";

        let obj= null;
        alert("Working! ");
        obj = new Car("Mini", 2001);
        obj.PrintDetails(); 

        document.addEventListener('DOMContentLoaded', function () {
            let obj2 = new Car("Merc", 2010);
            obj2.PrintDetails();
        });
    </script>
</head>
<body>
    <h1> Lets try something <br></h1>
</body>
</html>

My main.js file:我的 main.js 文件:

export class Car {
constructor(name, year) {
  this.name = name;
  this.year = year;

}
PrintDetails() {
    console.log(" Name = "+ this.name);
    console.log(" year = "+ this.year);
}

} }

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

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