javascript 如何使用 jQuery 将 <option> 插入到 <select> 多元素中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6922221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I insert an <option> into a <select> mutiple element using jQuery?
提问by Royal Pinto
How can I insert an <option>
into a <select>
(multiple) element using jQuery?
如何使用 jQuery将一个插入<option>
到<select>
(多个)元素中?
(I don't want to use select here. I want to use the element's ID so that I can use the same function for multiple elements.)
(我不想在这里使用 select。我想使用元素的 ID,以便我可以对多个元素使用相同的功能。)
Thanks.
谢谢。
回答by Molecular Man
$('#elementsID').append('<option>my new option</option>');
UPDATE
更新
to insert after option that lolks like <option value="value1">option with value1</option>
use:
在喜欢<option value="value1">option with value1</option>
使用的选项之后插入:
var newOption = $('<option value="newOpt">my new option</option>');
newOption.insertAfter('#elementsID option[value="value1"]');
回答by dpp
To appendan option:
要附加一个选项:
$('#colors').append('<option>red</option>');
To insertan option before or after another option:
要插入之前或之后的另一种选择一个选项:
$('<option>blue</option>').insertBefore("#colors option:contains('red')");
$('<option>yellow</option>').insertAfter("#colors option:contains('blue')");
To replacean option with another option:
为了替换另一个选项一个选项:
$("#colors option:contains('blue')").replaceWith("<option>pink</option>");
To replace alloptions:
要替换所有选项:
$('#colors')
.html("<option>green</option>" +
"<option>orange</option>" +
"<option>violet</option>");
回答by Raul Agrait
Looks like you want to use append. Example:
看起来你想使用append。例子:
var myOption = $("<option value='Option X'>X</option>");
$("#selectId").append(myOption);
If you want to insert items in between one another, you can use insertBeforeor insertAfter:
如果要在彼此之间插入项目,可以使用insertBefore或insertAfter:
myOption.insertAfter("$#idOfItemIWantToInsertAfter");