2011-03-21 21 views
8

使用jQuery爲給定選擇值編輯選項文本的最佳方式是什麼?使用jQuery設置<option>元素的文本

我知道我想要編輯的選項的值。我以爲它會是這樣的...

$('#select').val().$('option').html('New Text'); 

但我很明顯缺少一些東西。

+1

$('#select option:selected')。text(「new text」) – Bob 2011-03-21 16:42:00

回答

14
$('#select option[value="someValue"]').text("newText") 

可以使用替代.html.text,如果添加HTML內容。

4

你可能尋找:selected選擇和text()方法:

$("#select option:selected").text("New Text"); 
6

像這樣的事情?

$('#select').children('option').text('New Text'); 

查看Selectors關於選擇正確的項目的更多信息。你可以這樣做

$('#select').children('option:first').text('New Text'); 

或者你可以使用

$('#select').children('option[value="thevalue"]').text('New Text'); 

如果你知道值。

+0

它們都不適用於我,並且您在.children中有錯誤。 孩子以後沒有點 – 2014-02-23 20:42:20

2

這一個幫助你得到的期權價值,

$('#select_id').children('option[value="thevalue"]').text('New Text'); 

,您可以通過使用prop()功能設置默認選擇的值。舉一個例子here