伙计们,我刚开始学习打字稿,我试图用打字稿编写一个javascript示例,但是如果我运行代码并按下按钮,则什么也没发生。
由于我是Web编程的新手,但我在Java / python方面拥有多年经验,因此我也在寻找示例或资源来学习如何将Typescript集成到HTML中
typescript.ts
class Example{
constructor(){
let button=document.getElementById("b");
button.addEventListener("click", (e:Event)=>this.feedTheButton)
}
greatestOfTwo=(first:number,second:number):number=>{
if (first>second){
return first
}else{
return second
}
}
feedTheButton(){
let first:number = parseInt((<HTMLInputElement>document.getElementById("f")).value);
let second:number=parseInt((<HTMLInputElement>document.getElementById("d")).value);
let result:number=this.greatestOfTwo(first,second)
let place=document.getElementById("write")
place.innerHTML=result.toString()
}
}
new Example();
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="typescript.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>
Type a number
<input type="text" id="f" size="4">
</p>
<p> Type another number
<input type="text" id="s" size="4">
</p>
<button id="b" class="myButton" value="click">Get The Larger Number</button>
<P>The Larger number of the two is: <span id="wrote"></span></P>
</body>
</html>
答案 0 :(得分:-1)
直接将 this.feedTheButton 函数作为参数传递。
class Example{
constructor(){
let button=document.getElementById("b");
button.addEventListener("click", this.feedTheButton.bind(this)) // Directly pass the function as parameter
}
greatestOfTwo=(first:number,second:number):number=>{
if (first>second){
return first
}else{
return second
}
}
feedTheButton(e){
let first:number = parseInt((<HTMLInputElement>document.getElementById("f")).value);
let second:number=parseInt((<HTMLInputElement>document.getElementById("s")).value); // Changed this value to 's' because your input id is 's'
let result:number=this.greatestOfTwo(first,second)
let place=document.getElementById("wrote")
place.innerHTML=result.toString()
}
}
new Example();
您的html应该是这样的:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>
Type a number
<input type="text" id="f" size="4">
</p>
<p> Type another number
<input type="text" id="s" size="4">
</p>
<button id="b" class="myButton" value="click">Get The Larger Number</button>
<P>The Larger number of the two is: <span id="wrote"></span></P>
<script src="typescript.js"></script>
</body>
</html>