如何更改< select>的选项用jQuery? [英] How to change options of <select> with jQuery?
本文介绍了如何更改< select>的选项用jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设有可用的选项列表,如何用新的<option>
更新<select>
?
Suppose a list of options is available, how do you update the <select>
with new <option>
s?
推荐答案
您可以使用 empty
方法,然后添加新选项:
You can remove the existing options by using the empty
method, and then add your new options:
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);
如果对象中有新选项,则可以:
If you have your new options in an object you can:
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
编辑:要删除除第一个选项外的所有选项,可以使用 :gt
选择器,以获取索引大于零且 remove
他们:
For removing the all the options but the first, you can use the :gt
selector, to get all the option
elements with index greater than zero and remove
them:
$('#selectId option:gt(0)').remove(); // remove all options, but not the first
这篇关于如何更改< select>的选项用jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文