动态替换下拉菜单选项jQuery

Dynamically replace drop down menu options jQuery

本文关键字:jQuery 选项 下拉菜单 替换 动态      更新时间:2024-02-01

我有一个下拉菜单,我想在单击事件时更改其选择选项。当前的选择选项应被删除,并替换为新的选项阵列。小提琴来了:

这里还有另一个修复它的尝试,但没有成功:

 $(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);
            });
        });

您所要做的就是将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)
        }

DEMO

要清除select,请使用以下代码:

dropdown.empty();

http://jsfiddle.net/247z2/1/