如何使用jQuery将<option>移动到第二个位置?

3
我该如何使用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个回答

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

抱歉,我又不得不进行更改。我需要在一个 .each() 循环中完成它。此外,如果没有指定 value 属性,jQuery 将使用 >< 之间的值。 - cwd
@cwd:我已经更新了。你不能依赖于使用文本内容代替值属性的jQuery。这对于filter会起作用,但不一定适用于DOM选择。在Chrome中,这个例子将显示1而不是2个匹配元素。 - user1106925
谢谢。我已经接受了。从未测试过混合<option>值定义。+1 - 感谢分享。 - cwd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接