我目前正在尝试获取用户将插入输入表单的值。在 vanilla javascript 中,我可以通过 id 或 class 等来定位元素,然后我可以使用 .value 方法来实际使用该方法。出于某种原因,打字稿不能这样做,我不明白,因为打字稿是 javascript 的超集。有没有一种特定的方法可以从纯打字稿中的输入元素中获取值,还是我必须使用角度或其他东西?
打字稿代码:
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
});
原文由 AfternoonTiger 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您使用像 VSCode 这样的编辑器来编写 Typescript,我发现检查代码的能力对于了解更多关于打字系统中发生的事情非常有价值。在 VSCode 中,您可以右键单击方法(或类型)并选择
Go to definition
。检查您问题中的方法
getElementById
,您可以看到它返回一个HTMLElement
。这种类型没有value
属性。这是有道理的,因为getElementById
可以在页面上返回任何HTMLElement
只要它具有id
属性。 Not everyHTMLElement
though has avalue
property(for instance adiv
/span
/p
, etc) .因为你知道你期望什么类型,但是类型系统不能,为了让它工作,你必须告诉 Typescript 你期望选择什么类型的元素。您可以通过强制转换所选元素的类型来做到这一点,如下所示:
const inputElement = <HTMLInputElement> document.getElementById("food-name-val");
或const inputElement = document.getElementById("food-name-val") as HTMLInputElement;
现在,由于 Typescript 将所选元素识别为
HTMLInputElement
,因此当您访问value
属性时它不会出错。在您的情况下,这看起来像:
let foodName = (document.getElementById("food-name-val") as HTMLInputElement).value;