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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:13:38  来源:igfitidea点击:

Dynamically replace drop down menu options jQuery

javascriptjquery

提问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)
        }

DEMO

DEMO

回答by Alireza Fattahi

To clear the select use below code:

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

dropdown.empty();

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

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