简体   繁体   English

打字稿:按钮点击不调用功能

[英]Typescript: button click not calling function

I'm very new to typescript and I've been working on a simple typescript code where on button click, it will display an alert message in the browser. 我对打字稿很陌生,我一直在研究一个简单的打字稿代码,只需单击一下按钮,它就会在浏览器中显示警告消息。 I have tried using button and input tags, and also tried using an onclick event as well as an addEventListener. 我尝试使用按钮和输入标签,也尝试使用onclick事件以及addEventListener。 I'm not quite sure what the issue here is so any help given is highly appreciated. 我不太确定这里是什么问题,因此非常感谢您给予的任何帮助。

 //typescript portion of code document.getElementById("disp").addEventListener("click", (evt: Event) => this.disp_alrt()); function disp_alrt(){ alert("You pressed the button!"); } 
 <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <input type="button" class="button" id="disp" value="Display Alert"> </body> </html> 

You can trigger an event or alternatively set a callback 您可以触发事件或设置回调

 //typescript portion of code document.getElementById("disp").addEventListener("click", Event => this.disp_alrt()); document.getElementById("disp2").addEventListener("click", this.disp_alrt, true); function disp_alrt(event){ alert("You pressed the button!"); } 
 <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <input type="button" class="button" id="disp" value="Display Alert"> <input type="button" class="button" id="disp2" value="Display Alert2"> </body> </html> 

TypeScript is not JavaScript, To run typescript you need to transpile it to javascript you can paste your typescript code at playground and get javascript that will execute and understood by browsers. TypeScript不是JavaScript,要运行Typescript,您需要将其转换为javascript,您可以将您的typescript代码粘贴到操场上,并获取将由浏览器执行和理解的javascript。 Hope this is clear 希望这很清楚

I converted your event code document.getElementById("disp").addEventListener("click", (evt: Event) => this.disp_alrt()); 我转换了事件代码document.getElementById("disp").addEventListener("click", (evt: Event) => this.disp_alrt()); in playground and output was 在操场上,输出是

var _this = this;
document.getElementById("disp").addEventListener("click", function (evt) { return _this.disp_alrt(); });

https://www.typescriptlang.org/play/ https://www.typescriptlang.org/play/

 //typescript portion of code //var _this = this; function disp_alrt(){ alert("You pressed the button!"); } document.getElementById("disp").addEventListener("click", function (evt) { return disp_alrt(); }); 
 <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <input type="button" class="button" id="disp" value="Display Alert"> </body> </html> 

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

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