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

时间:2018-10-30 19:46:52

标签: javascript typescript

我目前正在尝试获取用户要插入输入表单的值。在香草javascript中,我可以按id或class等来定位元素,然后可以仅使用.value方法来实际使用该方法。由于某种原因,打字稿无法做到这一点,我不理解,因为打字稿是javascript的超集。是否有从纯打字稿中的输入元素获取值的特定方法,还是我必须使用angular或其他工具?

打字稿代码:

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
});

3 个答案:

答案 0 :(得分:3)

如果您检查了正在调用的方法(getElementById)后面的类型文件,则会看到它返回一个HTMLElement。此类型没有value属性。

所有HTML元素都继承自这一元素。为了使它起作用,您只需要让Typescript知道您期望选择的元素类型。您可以按照以下步骤进行操作:<HTMLInputElement> document.getElementById("food-name-val"),然后可以按以下方式访问其上的value属性:let foodName = (<HTMLInputElement> document.getElementById("food-name-val")).value;

答案 1 :(得分:1)

是的,TypeScript有这个“小问题”,但这是出于安全考虑。
您可以通过以下操作获取输入值:

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

您可以在此处查看有关这种投射<>的更多信息:TypeScript: casting HTMLElement

希望它能起作用!

答案 2 :(得分:0)

您可以在TypeScript中获得输入的值。 对于数字,

var num = parseFloat((<HTMLInputElement>document.getElementById("myValue")).value);
                                 or 
let num : number = parseFloat((<HTMLInputElement>document.getElementById("myValue")).value);

字符串;

var str = (<HTMLInputElement>document.getElementById("myUnit")).value; 
         or
let str : string = (<HTMLInputElement>document.getElementById("myUnit")).value; 

将HTMLElement强制转换为HTMLInputElement非常重要,否则TypeScript中HTMLElement的'value'属性不存在,并且TypeScript编译器将显示错误。

// 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 = (<HTMLInputElement>document.getElementById("food-name-val")).value;
  let foodCalories = parseFloat((<HTMLInputElement>document.getElementById("calories-val")).value);
  let dateVal = (<HTMLInputElement>document.getElementById("date-val")).value;
  // And so on ...
});