Javascript 从打字稿中的 <input> 元素获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53071851/
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
Getting the value from <input> element in typescript
提问by FanonX
I'm currently trying to get the values a user would insert into an input form. In vanilla javascript, I can just target the element by id or class, etc, and then I can just use the .value method to actually get in use that method. For some reason, typescript cannot do that, which I do not understand because typescript is a superset of javascript. Is there a specific way to get a value from an input element in pure typescript or do I have to use angular or something?
我目前正在尝试获取用户将插入到输入表单中的值。在 vanilla javascript 中,我可以通过 id 或 class 等来定位元素,然后我可以只使用 .value 方法来实际使用该方法。出于某种原因,打字稿不能做到这一点,我不明白,因为打字稿是 javascript 的超集。有没有一种特定的方法可以从纯打字稿中的输入元素中获取值,还是我必须使用 angular 之类的?
Typescript code:
打字稿代码:
interface IUserFoodOptions {
food: string;
calories: number;
foodDate: any;
}
class Food implements IUserFoodOptions {
food: string;
calories: number;
foodDate: any;
// store all the calories in an array and calculate the total amount of calories
caloriesArray: number[] = [];
// constructor
constructor(food: string, calories: number, foodDate: any) {
this.food = food;
this.calories = calories;
this.foodDate = foodDate;
}
}
// event listener for when the add food button is clicked
let addFood = document.getElementById("add-food-button").addEventListener("click", () => {
// get the values from inputs and store them in an array
let foodName = document.getElementById("food-name-val");
let foodCalories = document.getElementById("calories-val");
let dateVal = document.getElementById("date-val");
// store these values in a list and display them below
// user will have the ability to edit and delete them
// am I create event listeners within event listeners
});
回答by peinearydevelopment
If you are using an editor like VSCode to write Typescript, I've found the ability to inspect code very valuable in learning more about what's occurring in the typing system. In VSCode you can right click on the method(or type) and choose Go to definition.
如果你使用像 VSCode 这样的编辑器来编写 Typescript,我发现检查代码的能力对于了解更多关于打字系统中发生的事情非常有价值。在 VSCode 中,您可以右键单击方法(或类型)并选择Go to definition.
Inspecting the method in your question, getElementById, you can see it returns an HTMLElement. This type doesn't have a valueproperty on it. This makes sense as getElementByIdcan return any HTMLElementon the page as long as it has an idattribute. Not every HTMLElementthough has a valueproperty(for instance a div/span/p, etc).
检查您的问题中的方法getElementById,您可以看到它返回一个HTMLElement. 这种类型没有value属性。这是有道理的,因为只要它具有属性,getElementById就可以返回HTMLElement页面上的任何内容id。并不是每一个HTMLElement虽然有一个value属性(例如一个div/ span/p等)。
Since you know what type you are expecting, but the type system can't, to get this to work, you have to tell Typescript what type of element you expect to be selecting. You would do that through casting the type of the selected element as follows:
const inputElement = <HTMLInputElement> document.getElementById("food-name-val");or
const inputElement = document.getElementById("food-name-val") as HTMLInputElement;
既然你知道你期望什么类型,但类型系统不能,要让它工作,你必须告诉 Typescript 你期望选择什么类型的元素。你会做,通过铸造所选元素的类型如下:
const inputElement = <HTMLInputElement> document.getElementById("food-name-val");或
const inputElement = document.getElementById("food-name-val") as HTMLInputElement;
Now, since Typescript recognizes the selected element as an HTMLInputElement, it won't error when you access the valueproperty on it.
现在,由于 Typescript 将所选元素识别为HTMLInputElement,因此当您访问其value上的属性时不会出错。
In your case that would look like:
let foodName = (document.getElementById("food-name-val") as HTMLInputElement).value;
在您的情况下,它看起来像:
let foodName = (document.getElementById("food-name-val") as HTMLInputElement).value;
回答by Richard Nikolas
Yeah, TypeScript has this "little issue", but it is for safety.
You can get the input value doing something like this:
是的,TypeScript 有这个“小问题”,但这是为了安全。
您可以通过以下方式获取输入值:
var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;
You can see more about this casting <> thing here: TypeScript: casting HTMLElement
你可以在这里看到更多关于这个casting <>的东西:TypeScript:casting HTMLElement
Hope it works!
希望它有效!
回答by akolliy
You can get the value of an input in TypeScript. For a number,
您可以在 TypeScript 中获取输入的值。对于一个数,
var num = parseFloat((<HTMLInputElement>document.getElementById("myValue")).value);
or
let num : number = parseFloat((<HTMLInputElement>document.getElementById("myValue")).value);
Strings;
字符串;
var str = (<HTMLInputElement>document.getElementById("myUnit")).value;
or
let str : string = (<HTMLInputElement>document.getElementById("myUnit")).value;
It's important to cast HTMLElement to HTMLInputElement, otherwise 'value' property doesn't exist for HTMLElement in TypeScript and TypeScript compiler will show an error.
将 HTMLElement 转换为 HTMLInputElement 很重要,否则 TypeScript 中的 HTMLElement 不存在 'value' 属性,并且 TypeScript 编译器将显示错误。
// event listener for when the add food button is clicked
let addFood = document.getElementById("add-food-button").addEventListener("click", () => {
// get the values from inputs and store them in an array
let foodName = (<HTMLInputElement>document.getElementById("food-name-val")).value;
let foodCalories = parseFloat((<HTMLInputElement>document.getElementById("calories-val")).value);
let dateVal = (<HTMLInputElement>document.getElementById("date-val")).value;
// And so on ...
});

