我有一个选择框:

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>

我想将其中一个选项设置为“选定”基于它的选定索引。

例如,如果我试图设置“数字3”,我尝试这样做:

$('#selectBox')[3].attr('selected', 'selected');

但这行不通。我如何设置一个选项,因为选择基于它的索引使用jQuery?

谢谢!


当前回答

NB:

$('#selectBox option')[3].attr('selected', 'selected') 

是不正确的,数组遵从得到你的dom对象,而不是一个jquery对象,所以它将失败的TypeError,例如在FF与:"$('#selectBox选项')[3].attr()不是一个函数。"

其他回答

//funcion para seleccionar por el text del select
var text = '';
var canal = ($("#name_canal").val()).split(' ');
$('#id_empresa option').each(function(i, option) {
        text = $('#id_empresa option:eq('+i+')').text();
        if(text.toLowerCase() == canal[0].toLowerCase()){
            $('#id_empresa option:eq('+i+')').attr('selected', true);
        }
    });

试试这个吧:

$("#selectBox").val(3);

纯javascript selectedIndex属性是正确的方法,因为它是纯javascript,可以跨浏览器工作:

$('#selectBox')[0].selectedIndex=4;

这是一个jsfiddle演示,有两个下拉列表,使用一个来设置另一个:

<select onchange="$('#selectBox')[0].selectedIndex=this.selectedIndex">
  <option>0</option>
  <option>1</option>
  <option>2</option>
</select>

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
</select>

你也可以在改变selectedIndex之前调用它,如果你想要的是option标签上的“selected”属性(这里是fiddle):

$('#selectBox option').removeAttr('selected')
   .eq(this.selectedIndex).attr('selected','selected');

我需要一个解决方案,没有硬编码值在js文件;使用selectedIndex。大多数给出的解决方案在一个浏览器上失败。这似乎在FF10和IE8中工作(其他人能在其他版本中测试吗)

$("#selectBox").get(0).selectedIndex = 1; 

我也遇到过同样的问题。 首先你需要遍历事件(即哪个事件先发生)。

例如:

第一个事件是生成带有选项的选择框。

第二个事件是使用val()等函数选择默认选项。

您应该确保第二个事件应该发生在第一个事件之后。

为了实现这个目标,需要用到两个函数,比如generateSelectbox()(用于生成选择框)和selectDefaultOption()

您需要确保只有在generateSelectbox()执行之后才调用selectDefaultOption()