如何使用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);
});
答案 0 :(得分:6)
假设只有一个选择元素......
jQuery('option[value=eggplant]').insertAfter('option:first-child')
我还假设你的元素实际上有value
个属性。
问题中的代码发生了变化。现在它会......
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())
});