使用jQuery通过文本内容选择选项

One*_*Guy 76 jquery

我想为使用jquery通过查询字符串传递的任何内容设置一个下拉框.

如何将选定的属性添加到选项中,使"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
            });
        };
    });
Run Code Online (Sandbox Code Playgroud)

Pao*_*ino 172

替换这个:

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
});
Run Code Online (Sandbox Code Playgroud)

有了这个:

$('#cbCategory').val(cat);
Run Code Online (Sandbox Code Playgroud)

调用val()选择列表将自动选择具有该值的选项(如果有).

  • 这个答案已经过时了.从jQuery 1.4开始,`.val`只会在没有`value`属性的情况下通过文本内容选择选项.因此,如果选项元素具有值属性并且它们与文本内容不匹配,则此处提供的答案将不起作用. (15认同)
  • 我不能用这种方法选择多个选项吗? (2认同)
  • 此方法不会触发$('#cbCategory')元素上的事件. (2认同)

Gui*_*sta 34

我知道这个问题太旧了,但我认为这种方法会更清晰:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您不需要查看整个选项each().虽然到那个时候prop()并不存在,所以对于旧版本的jQuery使用attr().


UPDATE

使用时必须确定,contains因为你可以找到多个选项,如果字符串里面的字符串cat匹配的是与你想要匹配的选项不同的子字符串.

然后你应该使用:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);
Run Code Online (Sandbox Code Playgroud)

  • 感谢分享和保持最新的东西! (2认同)

Mar*_*ery 20

如果您的<option>元素没有value属性,那么您可以使用.val:

$selectElement.val("text_you're_looking_for")
Run Code Online (Sandbox Code Playgroud)

但是,如果您的<option>元素具有值属性,或者将来可能会这样做,那么这将无效,因为只要有可能,.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');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

将jQuery添加到页面后,只需在此处插入此插件即可

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
Run Code Online (Sandbox Code Playgroud)

选择选项.

该插件方法使用filter挑选出仅option匹配targetText,并且使用任一选择.attr.prop,取决于jQuery的版本(参见.prop(VS .attr)()用于解释).

这里有一个JSFiddle,您可以使用这个问题给出的所有三个答案,这表明这个是唯一可靠的工作:http://jsfiddle.net/3cLm5/1/