简体   繁体   中英

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. 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. Hope this is clear

I converted your event code 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/

 //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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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