简体   繁体   English

如何在 JavaScript 中获得 select 中的第一个选项?

[英]How do i get the first option in a select in JavaScript?

I want to get the first option from a select.我想从 select 中获得第一个选项。 Does this work?这行得通吗?

dropDown = document.querySelector(".select")
if (dropDown[0].innerHtml === '0'){
   console.log('yes')
}

dropDown is my select. dropDown是我的 select。 Inside there is option value=o>o</option .里面有option value=o>o</option This logs "yes" but it gives an error:这记录“是”,但它给出了一个错误:

Uncaught TypeError: dropDown[i] is undefined未捕获的类型错误:dropDown[i] 未定义

My rookie mind went this way:我的菜鸟想法是这样的:

const dropDown = document.querySelectorAll(".select > option")

if (dropDown[0].innerHtml === '0'){
   console.log('yes')
}

or if you need to have different types of actions based on the options:或者如果您需要根据选项执行不同类型的操作:

options.foreach(option => {
   switch(option.innerHTML) {
     case "value":
       // code block
       break;
     case "value2":
       // code block
       break;
     default:
       // code block
   }

Welcome to Stack Overflow.欢迎来到堆栈溢出。

dropDown = document.querySelector(".select") // this will always return only one element.
if (dropDown.innerHtml === '0'){ // So no need to add `dropdown.innerHTML[0]`
   console.log("yes");
}

Let me know if you need further support.如果您需要进一步的支持,请告诉我。

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

相关问题 当页面使用JavaScript / jQuery加载时,如何获取选择框的第一个选项以自动显示在div中? - How do I get the first option of a select box to display in a div automatically when the page loads with JavaScript/jQuery? 如何获得第二个选择选项以基于第一个选择选项显示 - How do I get second select option to show up based on first select option 如何在HTML中执行此SELECT / OPTION? (javascript) - How do I do this SELECT/OPTION in HTML? (javascript) 如何通过JavaScript获取<select>中当前选择的<option>? - How do you get the currently selected <option> in a <select> via JavaScript? 我如何使用 javascript 获得 select 选项中的值 - How i get the values in select option using javascript 如何获取当前行的选择选项的值 - How do I get value of select option for current row 如何使用jQuery在选择框选项中获取类的值 - how do I get the value of a class in the select box option with jquery 如何获得 React-Select 选项的值? - How do I get the value of the React-Select option? 我如何获取选择值而不是PHP中的选项值 - how do i get the select value not the option value in php 使用JavaScript,我如何重置表单中的所有选择,以便选择每个选项的第一个选项? - Using JavaScript, how can I reset all the select's in my form so that the first option for each is selected?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM