簡體   English   中英

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

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

我有一個.js文件,其中定義了一個類。 我想從另一個html文件中的<script>調用此類。

component.js:

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

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

main.html中:

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

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

<body>
</body>

當我加載main.html(來自我的網絡服務器)時,這不顯示警報。 但是,使用inspect控制台,我可以使用TryClass。

怎么解決這個?

經過測試我認為問題是你的格式

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

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

</head>

<body>

</body>

</html>

你在<script src="./component.js" /> </script>之后丟失了</script> ,我猜這是最糟糕的錯誤,雖然你也丟失了</html><head></head>

請試試

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