首页 > 解决方案 > 从中获取价值打字稿中的元素

问题描述

我目前正在尝试获取用户将插入输入表单的值。在 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
});

标签: javascripttypescript

解决方案


如果您使用 VSCode 之类的编辑器来编写 Typescript,我发现检查代码的能力对于更多地了解打字系统中发生的事情非常有价值。在 VSCode 中,您可以右键单击方法(或类型)并选择Go to definition.

检查您问题中的方法getElementById,您可以看到它返回一个HTMLElement. 此类型没有value属性。这是有道理的,因为只要它具有属性getElementById就可以返回页面上的任何内容。并非每个都具有属性(例如/ /等)。HTMLElementidHTMLElementvaluedivspanp

因为你知道你期望什么类型,但是类型系统不能,为了让它工作,你必须告诉 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;


推荐阅读