[英]Typescript: button click not calling function
我對打字稿很陌生,我一直在研究一個簡單的打字稿代碼,只需單擊一下按鈕,它就會在瀏覽器中顯示警告消息。 我嘗試使用按鈕和輸入標簽,也嘗試使用onclick事件以及addEventListener。 我不太確定這里是什么問題,因此非常感謝您給予的任何幫助。
//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>
您可以觸發事件或設置回調
//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不是JavaScript,要運行Typescript,您需要將其轉換為javascript,您可以將您的typescript代碼粘貼到操場上,並獲取將由瀏覽器執行和理解的javascript。 希望這很清楚
我轉換了事件代碼document.getElementById("disp").addEventListener("click", (evt: Event) => this.disp_alrt());
在操場上,輸出是
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.