【发布时间】:2019-04-03 22:34:08
【问题描述】:
我目前正在尝试获取用户将插入输入表单的值。在 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
});
【问题讨论】:
-
使用
as HTMLInputElement为我工作:stackoverflow.com/a/52495421/470749
标签: javascript typescript