javascript - 从中获取价值打字稿中的元素
问题描述
我目前正在尝试获取用户将插入输入表单的值。在 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
});
解决方案
如果您使用 VSCode 之类的编辑器来编写 Typescript,我发现检查代码的能力对于更多地了解打字系统中发生的事情非常有价值。在 VSCode 中,您可以右键单击方法(或类型)并选择Go to definition
.
检查您问题中的方法getElementById
,您可以看到它返回一个HTMLElement
. 此类型没有value
属性。这是有道理的,因为只要它具有属性getElementById
就可以返回页面上的任何内容。并非每个都具有属性(例如/ /等)。HTMLElement
id
HTMLElement
value
div
span
p
因为你知道你期望什么类型,但是类型系统不能,为了让它工作,你必须告诉 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;
推荐阅读
- java - 如何使用`Files.walk`和提前终止
- c# - 克隆对象中的 .NET 异常“对象当前在别处使用”
- javascript - 在多个 ES 模块上转换 Javascript“命名空间”
- flutter - pubspec.lock 的第 1 行第 1 列出错:意外字符
- winapi - HoloLens 的正确 WINAPI_FAMILY 是什么
- angular - (角度)错误类型错误无法读取未定义的属性“日期”
- c++ - 覆盖 QSpinBox 中的以下数字
- c# - Autofac 相当于 Unity 的 InjectionFactory
- vue.js - Vue.js pass local loop variable to v-bind:style
- python - 如何通过 DRF 中的 SELECT * LIKE 条件获取数据列表?