我有一个这样的下拉列表:

<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>

我如何才能获得实际的选项文本,而不是使用JavaScript的值?我可以通过如下方式获取值:

<select id="box1" onChange="myNewFunction(this.selectedIndex);" >

但我想要猫而不是7122。


当前回答

据我所知,有两种解决办法。

两者都只需要使用普通的javascript

1 selectedOptions

现场演示

const log = console.log; const areaSelect = document.querySelector(`[id="area"]`); areaSelect.addEventListener(`change`, (e) => { // log(`e.target`, e.target); const select = e.target; const value = select.value; const desc = select.selectedOptions[0].text; log(`option desc`, desc); }); <div class="select-box clearfix"> <label for="area">Area</label> <select id="area"> <option value="101">A1</option> <option value="102">B2</option> <option value="103">C3</option> </select> </div>

两个选择

现场演示

const log = console.log; const areaSelect = document.querySelector(`[id="area"]`); areaSelect.addEventListener(`change`, (e) => { // log(`e.target`, e.target); const select = e.target; const value = select.value; const desc = select.options[select.selectedIndex].text; log(`option desc`, desc); }); <div class="select-box clearfix"> <label for="area">Area</label> <select id="area"> <option value="101">A1</option> <option value="102">B2</option> <option value="103">C3</option> </select> </div>


其他回答

HTML:

<select id="box1" onChange="myNewFunction(this);">

JavaScript:

function myNewFunction(element) {
    var text = element.options[element.selectedIndex].text;
    // ...
}

演示:http://jsfiddle.net/6dkun/1/

纯JavaScript

var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;

jQuery:

$("#box1 option:selected").text();

试着选择

myNewFunction(sel) { alert (sel.options [sel.selectedIndex]。text); } <select id="box1" onChange="myNewFunction(this);" > 狗<选项值= " 98 " > < /选项> 猫<选项值= " 7122 " > < /选项> 鸟<选项值= " 142 " > < /选项> < /选择>

在React中使用Typescript:

  const handleSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (event) => {
    const {  options, selectedIndex } = event.target;
    const text = options[selectedIndex].text;
    // Do something...
  };

试试下面的方法:

myNewFunction = function(id, index) {
    var selection = document.getElementById(id);
    alert(selection.options[index].innerHTML);
};

请看这里的jsfiddle示例