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

使用jQuery,我想设置选择控件的选定元素为我有文本描述的项目(而不是值,这是我没有的)。

我知道用值来设置它很简单。如。

$("#my-select").val(myVal);

但我有点难住了,通过文本描述。我想一定有办法从文本描述中得到价值,但我的大脑在周五下午太忙了,无法解决这个问题。


当前回答

 $('#theYear').on('change', function () {
 FY = $(this).find('option:selected').text();
 $('#theFolders').each(function () {
     $('option:not(:contains(' + FY + '))', this).hide();
 });
 $('#theFolders').val(0);
});

$('#theYear').on('mousedown', function () {
 $('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});

其他回答

这句话很管用:

$("#myDropDown option:contains(myText)").attr('selected', true);

我还没有测试过,但这可能对你有用。

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });

我知道这是一篇老文章,但是我无法使用jQuery 1.10.3和上面的解决方案来实现文本选择。 我最终使用以下代码(spoulson的解决方案的变化):

      var textToSelect = "Hello World";

      $("#myDropDown option").each(function (a, b) {
            if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
        });

希望它能帮助到别人。

获取选择框的子元素;循环遍历它们;当你找到你想要的选项时,将其设置为所选选项;返回false停止循环。

非常精细,其他的似乎都不管用

选择美元(“[name = " dropdown’美元)。(儿童)短信先生(“”)。道具(selected, true);

为我工作。