如何使用jQuery更改<select>的选项?

假设有可用的选项列表,如何<select>用new来更新<option>



噜噜哒
浏览 1978回答 3
3回答

胡子哥哥

您可以使用empty方法删除现有选项,然后添加新选项:var option = $('<option></option>').attr("value", "option value").text("Text");$("#selectId").empty().append(option);如果对象中有新选项,则可以:var newOptions = {"Option 1": "value1",&nbsp; "Option 2": "value2",&nbsp; "Option 3": "value3"};var $el = $("#selectId");$el.empty(); // remove old options$.each(newOptions, function(key,value) {&nbsp; $el.append($("<option></option>")&nbsp; &nbsp; &nbsp;.attr("value", value).text(key));});编辑:要删除除第一个选项以外的所有选项,可以使用:gt选择器来获取option索引大于零的所有元素,以及remove它们:$('#selectId option:gt(0)').remove(); // remove all options, but not the first

慕妹3242003

我将CMS的出色答案放入了一个快速的jQuery扩展中:(function($, window) {&nbsp; $.fn.replaceOptions = function(options) {&nbsp; &nbsp; var self, $option;&nbsp; &nbsp; this.empty();&nbsp; &nbsp; self = this;&nbsp; &nbsp; $.each(options, function(index, option) {&nbsp; &nbsp; &nbsp; $option = $("<option></option>")&nbsp; &nbsp; &nbsp; &nbsp; .attr("value", option.value)&nbsp; &nbsp; &nbsp; &nbsp; .text(option.text);&nbsp; &nbsp; &nbsp; self.append($option);&nbsp; &nbsp; });&nbsp; };})(jQuery, window);它期望包含“文本”和“值”键的对象数组。因此用法如下:var options = [&nbsp; {text: "one", value: 1},&nbsp; {text: "two", value: 2}];$("#foo").replaceOptions(options);

慕哥6287543

$('#comboBx').append($("<option></option>").attr("value",key).text(value));其中comboBx是您的组合框ID。或者,您可以将选项作为字符串附加到已经存在的innerHTML中,然后分配给选择的innerHTML。编辑如果您需要保留第一个选项并删除所有其他选项,则可以使用var firstOption = $("#cmb1 option:first-child");$("#cmb1").empty().append(firstOption);
打开App,查看更多内容
随时随地看视频慕课网APP