简体   繁体   English

如何在 JavaScript 中使用 getElementByID 连接到我的 HTML 下拉框?

[英]How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options.我在 HTML 中有一个下拉框,显示三个选项。 I am also using javaScript and want to use the getElementById tool to connect the two.我也在使用 javaScript 并想使用 getElementById 工具将两者连接起来。 However, I only have one ID for the drop-down box.但是,我只有一个下拉框的 ID。 How does javascript recognize that I have three different options? javascript 如何识别我有三个不同的选项?

There's actually a demo on w3schools.com showing exactly what you're asking.实际上有一个关于 w3schools.com 的演示,准确地显示了您的要求。 To get the number of options, you could do something like要获得选项的数量,您可以执行类似的操作

document.getElementById("mySelect").options.length

Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/以下是如何检索下拉列表值的示例: https://jsfiddle.net/ykcwgnm8/

You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.您使用getElementBy*函数来获取元素,但是value属性表示当前选择了哪个项目。

HTML: HTML:

<select id="dropdown">
    <option value="1">First option</option>
    <option value="2">Second option</option>
    <option value="3">Third option</option>
</select>

JS: JS:

function onChangeHandler(e)
{
    alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);

You can listen for change like this你可以像这样倾听变化

 var list = document.getElementById("mySelect") list.addEventListener('change', function(e){ console.log(e.target.selectedIndex) console.log(e.target.options[e.target.selectedIndex].text) })
 <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select>

You can do something like this, here is an example:-你可以做这样的事情,这是一个例子: -

html html

<select id="selectBox">
  <option value="1">option 1</option>
  <option value="2" selected="selected">option 2</option>
  <option value="3">option 3</option>
</select>

js js

var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2

Hope you find this useful!!希望你觉得这个有用!!

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

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