javascript 如何在下拉菜单中获取所选文本而不是值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14165315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:53:28  来源:igfitidea点击:

How to get the selected text instead of value in dropdown menu

javascriptjquery

提问by FlyingCat

I am trying to get the user selected texts for my dropdown menu.

我正在尝试为我的下拉菜单获取用户选择的文本。

I have

我有

   var selectMenu=document.createElement('select');
            selectMenu.className='menu';

        for(var i=0; i<array.length; i++){

           var option=document.createElement('option');
               option.className='option';
               option.innerHTML=array[i].name;
               option.value=array[i].id;

            selectMenu.appendChild(option);
         }

         $(selectMenu).change(function(){

           //i want to get the selected text here

           //I know I could get value by using $(this).val()
           //but not sure how to get the selected text here.

         })

I have google the issue and all I found are like

我用谷歌搜索了这个问题,我发现的一切都像

$('#menu option:selected).text().

Are there anyways to get what I need? Thanks a lot!

有没有办法得到我需要的东西?非常感谢!

回答by Rafay

if you have something like

如果你有类似的东西

<select>
    <option value='1'> SO</option>
    <option value='2'>GOOGLE</option>
</select>

you can try

你可以试试

$("select").change(function(e){
    console.log($(":selected",this).text());
});

http://jsfiddle.net/Ykzp7/

http://jsfiddle.net/Ykzp7/

回答by obs

try $('.menu option:selected).text()instead of $('#menu...

尝试$('.menu option:selected).text()而不是$('#menu...