使用JQuery清除下拉列表 [英] Clear dropdownlist with JQuery

查看:155
本文介绍了使用JQuery清除下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这个小函数,用服务器中的数据填充下拉列表。

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...






还有 a更简洁的方法建立选项:

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

这篇关于使用JQuery清除下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆