使用 jQuery 按文本内容选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1009740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting option by text content with jQuery
提问by OneSmartGuy
I want to set a dropdown box to whatever has been passed through a querystring using jquery.
我想将下拉框设置为使用 jquery 通过查询字符串传递的任何内容。
How do I add the selected attribute to an option such that the "TEXT" value is equal to a certain param from the query string?
如何将 selected 属性添加到选项,以便“TEXT”值等于查询字符串中的某个参数?
$(document).ready(function() {
var cat = $.jqURL.get('category');
if (cat != null) {
cat = $.URLDecode(cat);
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
};
});
回答by Paolo Bergantino
Replace this:
替换这个:
var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
With this:
有了这个:
$('#cbCategory').val(cat);
Calling val()
on a select list will automatically select the option with that value, if any.
调用val()
选择列表将自动选择具有该值的选项(如果有)。
回答by Guilherme David da Costa
I know this question is too old, but still, I think this approach would be cleaner:
我知道这个问题太老了,但我仍然认为这种方法会更清晰:
cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
In this case you wont need to go over the entire options with each()
.
Although by that time prop()
didn't exist so for older versions of jQuery use attr()
.
在这种情况下,您无需使用each()
. 虽然到那时prop()
还不存在,所以对于旧版本的 jQuery 使用attr()
.
UPDATE
更新
You have to be certain when using contains
because you can find multiple options, in case of the string inside cat
matches a substring of a different option than the one you intend to match.
使用时必须确定,contains
因为您可以找到多个选项,以防里面的字符串cat
匹配与您打算匹配的选项不同的选项的子字符串。
Then you should use:
那么你应该使用:
cat = $.URLDecode(cat);
$('#cbCategory option')
.filter(function(index) { return $(this).text() === cat; })
.prop('selected', true);
回答by Mark Amery
If your <option>
elements don't have value
attributes, then you can just use .val
:
如果您的<option>
元素没有value
属性,那么您可以使用.val
:
$selectElement.val("text_you're_looking_for")
However, if your <option>
elements have value attributes, or might do in future, then this won't work, because whenever possible .val
will select an option by its value
attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value
attributes, so we'll have to add one ourselves with a simple plugin:
但是,如果您的<option>
元素具有 value 属性,或者将来可能会这样做,那么这将不起作用,因为只要有可能,.val
将通过其value
属性而不是其文本内容来选择一个选项。如果选项具有value
属性,则没有内置的 jQuery 方法可以通过文本内容选择选项,因此我们必须使用一个简单的插件自己添加一个:
/*
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');
}
});
}
Just include this plugin somewhere after you add jQuery onto the page, and then do
将 jQuery 添加到页面后,只需在某处包含此插件,然后执行
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
to select options.
选择选项。
The plugin method uses filter
to pick out only the option
matching the targetText, and selects it using either .attr
or .prop
, depending upon jQuery version (see .prop() vs .attr()for explanation).
插件方法用于filter
仅选择option
匹配的目标文本,并使用.attr
或选择它.prop
,具体取决于 jQuery 版本(有关说明,请参阅.prop() 与 .attr())。
Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/
这是一个 JSFiddle,你可以用来玩这个问题的所有三个答案,这表明这是唯一一个可靠地工作的答案:http: //jsfiddle.net/3cLm5/1/