简体   繁体   English

打字稿:遍历下拉列表

[英]Typescript: Iterate through a dropdown

I am new to Typescript and I have a dropdown whose values I need to iterate through. 我是Typescript的新手,我有一个下拉列表,需要对其进行迭代。 This is the code I am trying: 这是我正在尝试的代码:

var sortBy = document.getElementById("SortbySel");

I want to iterate through the options but since this is an HTMLElement, I am unable to do so. 我想遍历这些选项,但是由于这是HTMLElement,所以无法这样做。 What would be the best way to do this? 最好的方法是什么?

One way would be to use the querySelectorAll function: 一种方法是使用querySelectorAll函数:

var options = document.querySelectorAll('#SortbySel option');
for(var i = 0; i < options.length; i++){
    console.log(options.item(i).value);
}

Check out this stackblitz POC where I iterated over select HTML element 在我遍历select HTML element地方查看这个 stackblitz POC

If you are using typescript it is always better to use specific classes like HTMLSelectElement & HTMLOptionElement instead of using conventional var declarations as it helps a lot in intellisense. 如果您使用的是typescript ,则最好使用诸如HTMLSelectElementHTMLOptionElement类的特定类,而不是使用常规的var声明,因为这样做有助于智能感知。

the code looks like this - 代码看起来像这样-

let selectElement: HTMLSelectElement = 
document.getElementById('select') as HTMLSelectElement;

for (let i = 0; i < selectElement.options.length; i++) {
  let option: HTMLOptionElement = selectElement.options[i];
  console.log(option);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM