使用 jquery 按文本设置下拉值 [英] set dropdown value by text using jquery
本文介绍了使用 jquery 按文本设置下拉值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个下拉列表:
<select id="HowYouKnow" >
<option value="1">FRIEND</option>
<option value="2">GOOGLE</option>
<option value="3">AGENT</option></select>
在上面的下拉列表中,我知道下拉列表的文本.如何使用 jquery 使用文本设置 document.ready 中下拉列表的值?
In the above dropdown i know the text of the dropdown. How can set the value of the dropdown in document.ready with the text using jquery?
推荐答案
这是一种基于选项的文本 而不是索引的方法.刚刚测试.
This is a method that works based on the text of the option, not the index. Just tested.
var theText = "GOOGLE";
$("#HowYouKnow option:contains(" + theText + ")").attr('selected', 'selected');
或者,如果有相似的值(感谢 shanabus):
Or, if there are similar values (thanks shanabus):
$("#HowYouKnow option").each(function() {
if($(this).text() == theText) {
$(this).attr('selected', 'selected');
}
});
这篇关于使用 jquery 按文本设置下拉值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文