如何使用jQuery将<option>移动到第二个元素?</option>

时间:2011-12-27 03:31:23

标签: jquery

如何使用jQuery将特定的<option>移动到第二个选项?

<select class="comestibles">
 <option>apple</option>
 <option>banana</option>
 <option>cantaloupe</option>
 <option>date</option>
 <option>eggplant</option>
 <option>fig</option>
</select>

<select class="comestibles">
 <option>apple</option>
 <option>banana</option>
 <option>cantaloupe</option>
 <option>date</option>
 <option>eggplant</option>
 <option>fig</option>
</select>

此代码会使eggplant成为第一个选项...关闭但没有雪茄。

jQuery('select.comestibles').each(function(){
  $('option[value=eggplant]',this).prependTo(this);
}); 

1 个答案:

答案 0 :(得分:6)

假设只有一个选择元素......

jQuery('option[value=eggplant]').insertAfter('option:first-child')

我还假设你的元素实际上有value个属性。

http://jsfiddle.net/wNmLF/


问题中的代码发生了变化。现在它会......

jQuery('select.comestibles option[value=eggplant]').insertAfter('select.comestibles option:first-child')

对于最近的变化......

jQuery('select.comestibles').each(function(){
    var opts = $(this).children();
    opts.filter('[value=eggplant]').insertAfter(opts.first())
});