jQuery - 通过文本描述设置选择控件的选定值 [英] jQuery - setting the selected value of a select control via its text description
问题描述
我有一个select控件,在javascript变量中我有一个文本字符串。
I have a select control, and in a javascript variable I have a text string.
使用jQuery我想将select控件的selected元素设置为我有文本描述的项目(而不是我没有的值)。
Using jQuery I want to set the selected element of the select control to be the item with the text description I have (as opposed to the value, which I don't have).
我知道按值设置它是非常简单的。例如。
I know setting it by value is pretty trivial. e.g.
$("#my-select").val(myVal);
但是通过文字描述我有点难过。我想必须有一种从文本描述中获取价值的方法,但是我的大脑在星期五下午也能够解决它。
But I'm a bit stumped on doing it via the text description. I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out.
推荐答案
鉴于此HTML:
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
按jQuery v1.6 +的说明选择:
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).prop('selected', true);
按描述选择低于1.6且大于或等于1.4的jQuery版本:
https://stackoverflow.com/a/3644500/31532
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).attr('selected', true);
请注意,虽然这种方法适用于1.6以上但小于1.9的版本,但它一直是从1.6开始弃用。它在jQuery 1.9+中 将无效 。
Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.
按先前版本的说明选择:
val()
应该处理这两种情况。你没有看到吗?
val()
should handle both cases. Are you not seeing it?
例如:
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
这篇关于jQuery - 通过文本描述设置选择控件的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!