I wrote this little function to fill a drop down list with data from the server.

function fillDropDown(url, dropdown) {
    $.ajax({
        url: url,
        dataType: "json"
    }).done(function (data) {
        // Clear drop down list
        $(dropdown).find("option").remove(); <<<<<< Issue here
        // Fill drop down list with new data
        $(data).each(function () {
            // Create option
            var $option = $("<option />");
            // Add value and text to option
            $option.attr("value", this.value).text(this.text);
            // Add option to drop down list
            $(dropdown).append($option);
        });
    });
}

I can then call the function in this way:

fillDropDown("/someurl/getdata", $("#dropdownbox1"))

Everything is working perfectly, except for the one line where I'm clearing old data from the drop down list. What am I doing wrong?

Any tips that might help to improve this code are also highly appreciated.

推荐答案

只要用.empty():

// snip...
}).done(function (data) {
    // Clear drop down list
    $(dropdown).empty(); // <<<<<< No more issue here
    // Fill drop down list with new data
    $(data).each(function () {
        // snip...

There's also a more concise way to build up the options:

// snip...
$(data).each(function () {
    $("<option />", {
        val: this.value,
        text: this.text
    }).appendTo(dropdown);
});

Jquery相关问答推荐

为什么函数没有进入

从 React 到 Node 服务器的 ajax 调用中的数据未定义

JQuery:$.get 不是函数

jQueryUI 模态对话框不显示关闭按钮 (x)

jQuery - 向下滚动时缩小的粘性标题

jQuery 与 javascript?

jQuery.parseJSON 单引号与双引号

字符串化(转换为 JSON)具有循环引用的 JavaScript 对象

jQuery .load() 调用不会在加载的 HTML 文件中执行 JavaScript

所有选中复选框的 jQuery 数组(按类)

jQuery 插件:添加回调功能

将打开/关闭图标添加到 Twitter Bootstrap 可折叠项(手风琴)

JavaScript:让代码每分钟运行一次

判断文本框是否有空值

jquery分别绑定双击和单击

使用 jQuery 获取选中复选框的值

在 jquery 中使用 AJAX Post 从强类型 MVC3 视图传递模型的正确方法

Chrome 中的 AJAX 发送选项而不是 GET/POST/PUT/DELETE?

fancybox2 / fancybox 导致页面跳转到顶部

jquery在cookie中保存json数据对象