typescript 从您的 html 按钮 onclick 事件调用打字稿方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45544752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:46:32  来源:igfitidea点击:

Calling a typescript method from your html button onclick event

typescript

提问by user3750290

I am new to typescript. I have a query on how to call a method inside a .ts file from your .html page when u click a html button

我是打字稿的新手。我有一个关于如何在您单击 html 按钮时从 .html 页面调用 .ts 文件中的方法的查询

.ts file

.ts 文件

class AdminTS {
    public alertMessageTS() {
        alert("This is the test call!!!.");
    }
}

.html page

.html 页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>
        Sample TypeScript page
    </title>
    <script src="AdminTS.js"></script>
</head>
<body>
    <input type="button" value="Click" onclick ="getTrainingName(1)">
    </input>
</body>
</html>

I am getting a runtime exception saying getTrainingName is undefined.

我收到一个运行时异常,说 getTrainingName 未定义。

回答by Kokodoko

getTrainingName()is never defined in your example code, perhaps you forgot to add that part?

getTrainingName()从未在您的示例代码中定义,也许您忘记添加该部分?

I would suggest not using javascript at all in your html, instead use addEVentListenerto add handlers to dom elements. Then all your application logic will be in *.tsfiles.

我建议在您的 html 中根本不使用 javascript,而是使用addEVentListener向 dom 元素添加处理程序。然后你所有的应用程序逻辑都将在*.ts文件中。

(Since you already work with typescript it makes even less sense to add inline js in html)

(由于您已经使用过打字稿,因此在 html 中添加内联 js 就更没有意义了)

.html file

.html 文件

<input type="button" value="Click" id="coolbutton"></input>

.ts file

.ts 文件

class AdminTS {
  constructor() {
    let btn = document.getElementById("coolbutton");
    btn.addEventListener("click", (e:Event) => this.getTrainingName(4));
  }
  getTrainingName(n:number){
     // button click handler
  }
}

// start the app
new AdminTS();