如何使用事件监听器从选择标签中获取选择的文本? [重复]

的HTML

<select id='alpha'>
  <option value='1'>one</option>
  <option value='2'>two</option>
</select>

JAVASCRIPT

const select_node = document.getElementById('alpha');
select_node.addEventListener('change', (e)=>{
console.log(e.target.value); // get selected value.
   },false);

我正在获得选定的值,但是如何获得选定的文本? 我已经尝试谷歌,但什么也没找到。 那么,如何使用事件监听器获取选定的文本?

评论
  • 嘟嘟嘴
    嘟嘟嘴 回复

    You need to access the dropwdown's options at the dropdown's selectedIndex:

    var select_node = document.getElementById("alpha");
    select_node.addEventListener('change', (e)=>{
       console.log(e.target.options[e.target.selectedIndex].text); // get selected value.
    });
    
  • gcum
    gcum 回复

    尝试:

    e.target.options[e.target.selectedIndex].text
    

    .options property collects all of the <select> <option>s

    .selectedIndex property returns the current index number of selected <option>

    .text property of course is the text within an <option>TEXT</option>

    const select_node = document.getElementById('alpha');
    select_node.addEventListener('change', (e) => {
      console.log(e.target.value); // get selected value.
      console.log(e.target.options[e.target.selectedIndex].text); // get selected text.
    }, false);
    <select id='alpha'>
      <option value='1'>one</option>
      <option value='2'>two</option>
    </select>