Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

javascript - jQuery - 通过文本描述设置选择控件的选定值(jQuery - setting the selected value of a select control via its text description)

I have a select control, and in a javascript variable I have a text string.

(我有一个选择控件,在一个javascript变量中我有一个文本字符串。)

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).

(使用jQuery我想将select控件的selected元素设置为具有我所拥有的文本描述的项目(而不是我没有的值)。)

I know setting it by value is pretty trivial.

(我知道按值设置它是非常微不足道的。)

eg

(例如)

$("#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.

(我想必须有一种从文本描述中获取价值的方法,但是我的大脑在星期五下午也可以解决它。)

  ask by DanSingerman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Select by description for jQuery v1.6+(按jQuery v1.6 +的描述选择)

 var text1 = 'Two'; $("select option").filter(function() { //may want to use $.trim in here return $(this).text() == text1; }).prop('selected', true); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select> <option value="0">One</option> <option value="1">Two</option> </select> 

jQuery versions below 1.6 and greater than or equal to 1.4(jQuery版本低于1.6且大于或等于1.4)

 var text1 = 'Two'; $("select option").filter(function() { //may want to use $.trim in here return $(this).text() == text1; }).attr('selected', true); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script> <select> <option value="0">One</option> <option value="1">Two</option> </select> 

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.

(请注意,虽然此方法适用于1.6以上但小于1.9的版本,但自1.6以来已被弃用。)

It will not work in jQuery 1.9+.

(它不适用于jQuery 1.9+。)


Previous versions(之前的版本)

val() should handle both cases.

(val()应该处理这两种情况。)

 $('select').val('1'); // selects "Two" $('select').val('Two'); // also selects "Two" 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <select> <option value="0">One</option> <option value="1">Two</option> </select> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...