如何选中html中下拉列表中的选项的文字

来源:互联网 发布:甲骨文软件学院 编辑:程序博客网 时间:2024/04/28 21:37

现在我们有一个下拉列表,Html代码如下:

<select id="fruit_type">    <option value ="f1">Apple</option>    <option value ="f2">Banana</option>    <option value ="f3">Orange</option>    <option value ="f4">Pearl</option></select>


这个是时候我们想拿到选中的水果的名字,比如Apple,下面的代码不行:



var fruit_select = document.getElementById("fruit_type");var fruit_name = fruit_select.value;

这个时候只能拿到水果的id,比如 f1


这时需要先得到选中的菜单项的index,再取文字


var fruit_select = document.getElementById("fruit_type");var fruit_index=fruit_type_select.selectedIndex;
// 这行会返回 f1var fruit_id = fruit_type_select.options[fruit_type_index].value;
// 这行才能返回我们想要的 Applevar fruit_name = fruit_type_select.options[fruit_type_index].text;







                                             
0 0
原创粉丝点击