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

<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

onChange = { e => e.currentTarget.options[e.selectedIndex].text }

如果值在循环中,会给你精确的值。

其他回答

函数runCode() { var value = document.querySelector('#Country').value; window.alert(文档。querySelector(#国家选项(value = $ {value}]) .innerText); } <select name="Country" id="Country"> 印度<选项值= " " > < /选项> <option value="GBR">United Kingdom </option> . " /option> . <option value="USA">美国</option> <option value="URY">乌拉圭</option> . <option value="UZB">乌兹别克斯坦</option> < /选择> <按钮onclick = " runCode ()按钮“> < / >

使用jquery。 在你看来

  let selText = $("#box1 option:selected").text();
  console.log(selText);

您需要获取该选项的innerHTML,而不是它的值。

用这个。innerHTML代替this.selectedIndex。

编辑:首先需要获取option元素,然后使用innerHTML。

用这个。text代替this.selectedIndex。

试着选择

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