简体   繁体   English

如何从 select 菜单中选择 select 文本选项

[英]How to select text option from select menu

I am attempting to select the text that is shown in my select menu.我正在尝试 select 显示在我的 select 菜单中的文本。 On change I would like to know what text was select and not the value.在更改时,我想知道什么文本是 select 而不是值。

I am able to do this for the value with this.value but when attempting to do this.label or this.text I am getting an undefined return.我可以使用this.value为值执行此操作,但是当尝试执行this.labelthis.text时,我得到了未定义的返回。

How can I get the text shown in the drop down menu and not the value?如何获取下拉菜单中显示的文本而不是值?

If I do this.title then its showing the title of my select menu not the actual the title of the option如果我这样做this.title那么它显示我的 select 菜单的标题而不是选项的实际标题

Here is an example of my code:这是我的代码示例:

 $("#test").change(function() { let selectValue = this.value console.log(selectValue) let title = this.title console.log((this.options[this.selectedIndex])) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="test" title="test"> <option value="high school">Academic</option> <option value="online">Retail</option> </select>

I am expecting to see a return value "Academic" and not "high school" or "Retail" and not "online"我希望看到返回值“学术”而不是“高中”或“零售”而不是“在线”

Get the selected option by this.options and this.selectedIndex通过this.optionsthis.selectedIndex获取选中的选项

console.log(this.options[this.selectedIndex])

 $("#test").change(function() { let selectedOption = this.options[this.selectedIndex]; console.log(selectedOption.innerHTML); console.log($(selectedOption).text()); console.log($(selectedOption).html()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="test" title="test"> <option value="high school">Academic</option> <option value="online">Retail</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM