简体   繁体   English

如何在html中使用外部Javascript类?

[英]How to use a external Javascript class in html?

I have a .js file which has a class defined. 我有一个.js文件,其中定义了一个类。 I want to call this class from <script> from another html file. 我想从另一个html文件中的<script>调用此类。

component.js: component.js:

class TryClass {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    alert( this.name );
  }
}

main.html: main.html中:

<html>
<script src="./component.js" />

<script>
var user = new TryClass( "John" );
user.sayHi();
</script>

<body>
</body>

This doesn't show the alert when I load main.html (from my webserver). 当我加载main.html(来自我的网络服务器)时,这不显示警报。 However, with the inspect console, I am able to use the TryClass. 但是,使用inspect控制台,我可以使用TryClass。

How to resolve this? 怎么解决这个?

after test i think the problem is your format 经过测试我认为问题是你的格式

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="component.js"></script>
    <script>
        var user = new TryClass("John");
        user.sayHi();
    </script>

</head>

<body>

</body>

</html>

you lost </script> after <script src="./component.js" /> ,i guess this is the worst error though you also lost </html> and <head></head> 你在<script src="./component.js" /> </script>之后丢失了</script> ,我猜这是最糟糕的错误,虽然你也丢失了</html><head></head>

Please try by 请试试

var TryClass = function(name){
    this.name = name;
}

TryClass.prototype.sayHi = function () {
    alert( this.name );
}

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

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