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

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

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

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

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


当前回答

这句话很管用:

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

其他回答

 $('#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');
});

为了避免所有jQuery版本的复杂性,我真诚地建议使用这些非常简单的javascript函数之一…

function setSelectByValue(eID,val)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].value==val) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

function setSelectByText(eID,text)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].text==text) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

试试这个…选择myText文本选项

$("#my-Select option[text=" + myText +"]").prop("selected", true);
$("#myselect option:contains('YourTextHere')").val();

将返回包含文本描述的第一个选项的值。测试了这一点,并工作。

根据描述选择jQuery v1.6+

var text1 = '两个'; $("select option").filter(function() { //可能需要使用$。这里修剪一下 返回$(this).text() == text1; })。道具(“选择”,真正的); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <选择> <选项值= " 0 " > < /选项>一个 两个<选项值= " 1 " > < /选项> < /选择>

jQuery版本低于1.6且大于等于1.4

var text1 = '两个'; $("select option").filter(function() { //可能需要使用$。这里修剪一下 返回$(this).text() == text1; })。attr(‘选择’,真正的); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js " > < /脚本> <选择> <选项值= " 0 " > < /选项>一个 两个<选项值= " 1 " > < /选项> < /选择>

注意,虽然这种方法可以在高于1.6但低于1.9的版本中工作,但从1.6开始就已经弃用了。它不能在jQuery 1.9+中工作。


以前的版本

Val()应该处理这两种情况。

$('选择').val (' 1 ');//选择“2” $('选择').val(两个);//同时选择"Two" < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js " > < /脚本> <选择> <选项值= " 0 " > < /选项>一个 两个<选项值= " 1 " > < /选项> < /选择>