javascript 动态替换下拉菜单选项 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20315923/
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
Dynamically replace drop down menu options jQuery
提问by wootscootinboogie
I have a drop down menu whose select options I would like to change on a click event. The current select options should be removed and replaced with a new array of options. Here's the fiddle:
我有一个下拉菜单,我想在单击事件时更改其选择选项。当前的选择选项应该被删除并替换为一组新的选项。这是小提琴:
And here's another attempt at fixing it that doesn't work:
这是修复它的另一种尝试,但不起作用:
$(document).ready(function () {
var dropdown = $('<select>');
dropdown.options = function (data) {
var self = this;
if (data.length > 0) {
//how to remove the current elements
}
$.each(data, function (ix, val) {
var option = $('<option>').text(val);
data.push(option);
});
self.append(data)
}
dropdown.clear = function () {
this.options([]);
}
var array = ['one', 'two', 'three'];
dropdown.options(array);
$('body').append(dropdown);
$('#btnSubmit').on('click', function (ix, val) {
//should clear out the current options
//and replace with the new array
var newArray = ['four', 'five', 'six'];
dropdown.clear();
dropdown.options(newArray);
});
});
回答by charlietfl
All you have to do is change append()
to html()
since html()
replaces existing content of element
您所要做的就是更改append()
为html()
因为html()
替换元素的现有内容
dropdown.options = function (data) {
var self = this;
$.each(data, function (ix, val) {
var option = $('<option>').text(val).val(val);/* added "val()" also*/
data.push(option);
});
self.html(data)
}
回答by Alireza Fattahi
To clear the select use below code:
要清除选择,请使用以下代码:
dropdown.empty();