如果您<option>
元素没有value
属性,那么你可以使用.val
:
$selectElement.val("text_you're_looking_for")
但是,如果你<option>
元素具有价值属性,或在将来可能会做,那么这将无法工作,因为只要有可能.val
将其value
属性,而不是通过选择一个选项,它的文本内容。有没有内置的jQuery的方法,如果选择有value
属性,将选择其文本内容的选项,所以我们需要增加一个我们用一个简单的插件:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function() {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function() {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
就包括这个插件后某处你添加jQuery到页面上,然后做
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
来选择选项。
插件方法使用filter
挑选出仅option
匹配targetText,并使用任一.attr
.prop
或取决于jQuery的版本选择它(参见.prop() vs .attr()用于解释)。
这里有一个的jsfiddle你可以用给定了这个问题,这表明这个人是可靠地工作的唯一一个所有三个答案玩:jQuery的的http://jsfiddle.net/3cLm5/1/
可能重复 - 设置的选定值选择控制通过它的文字描述](http://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description) – 2013-07-01 21:44:46