从打字稿中的 <input> 元素获取值

新手上路,请多包涵

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

阅读 496
2 个回答

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

检查您问题中的方法 getElementById ,您可以看到它返回一个 HTMLElement 。这种类型没有 value 属性。这是有道理的,因为 getElementById 可以在页面上返回任何 HTMLElement 只要它具有 id 属性。 Not every HTMLElement though has a value property(for instance a div / 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;

原文由 peinearydevelopment 发布,翻译遵循 CC BY-SA 4.0 许可协议

是的,TypeScript 有这个“小问题”,但这是为了安全。

您可以通过以下方式获取输入值:

 var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;

您可以在此处查看有关此铸造 <> 的更多信息: TypeScript:铸造 HTMLElement

希望它有效!

原文由 Richard Nikolas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏