2011-12-27 27 views
3

如何使用jQuery將特定的<option>作爲第二個選項?如何使用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); 
}); 

回答

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

你不需要http://jsfiddle.net/wNmLF/1/ – qwertymk 2011-12-27 03:39:07

+0

對不起,我不得不再次改變它。我需要在'.each()'循環中完成。如果沒有指定'value'屬性,jQuery將使用'>'和'<'之間的值。 – cwd 2011-12-27 03:39:17

+0

@cwd:我更新了。而且你不能依靠jQuery使用文本內容來代替value屬性。它將用於「過濾器」,但不一定用於DOM選擇。在Chrome中,[此示例](http://jsfiddle.net/wNmLF/2/)將顯示1而不是2個匹配的元素。 – 2011-12-27 03:47:31

相關問題