html选择列表 - 通过传递变量获取文本值? [英] html select list - get text value by passing in a variable?

查看:89
本文介绍了html选择列表 - 通过传递变量获取文本值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示列表语言的选择列表。

 < select name =language_codeid =id_language_code > 
< option value =ar>阿拉伯语 - العربية< / option>
< option value =bg>保加利亚语 - Български< / option>
< option value =zh-CN>中文(简体) - 中文(简体)< / option>
< option value =enselected =selected>英语(美国)< / option>
< option value =fr-CA>法语(加拿大) - français(加拿大)< / option>
< / select>

我可以使用所选值的文字值以下代码[从上面的选择列表中返回英语(美国)]:

  $('#id_language_code option:selected')。 text()

如果我传递选项值' bg'作为一个变量,当选择的值仍然是英语(美国)?

这意味着返回的值将是保加利亚 - Български选择的值仍然是英语(美国)。



我已经搜索了Google和SO以获得答案,但无法找到答案,所以我认为这是不像我第一次想到的那样容易!

解决方案

这是一个如何使用CSS选择器来查询 value 属性:

  function getOptionTextByValue(value){
return $('#id_language_code option [va lue ='+ value +']')。text();
}

var bgText = getOptionTextByValue('bg');

下面是一个工作示例
http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview


I have a select list that displays a list languages.

<select name="language_code" id="id_language_code">
    <option value="ar">Arabic - العربية</option>
    <option value="bg">Bulgarian - Български</option>
    <option value="zh-CN">Chinese (Simplified) - 中文 (简体)‎</option>
    <option value="en" selected="selected">English (US)</option>
    <option value="fr-CA">French (Canada) - français (Canada)‎</option>
</select>

I am able to get the text value of the selected value using the following code [returns English (US) from the above select list]:

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

How can I get the text value if I pass the option value of 'bg' as a variable when the selected value is still English (US)?

This means that the value returned would be "Bulgarian - Български" when the selected value is still "English (US)".

I have searched Google and SO for an answer, but was unable to find one, so I am thinking that this is not as easy as I 1st thought it was!

解决方案

Here is an example of how you can use CSS selectors to query the value attribute:

function getOptionTextByValue(value) {
  return $('#id_language_code option[value=' + value +  ']').text();
}

var bgText = getOptionTextByValue('bg');

Here is a working example http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview

这篇关于html选择列表 - 通过传递变量获取文本值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆