Javascript空select

Javascript Empty select

我有一个 <select> 从数组填充的代码:

<select id="selector" name="selector"</select>
<button type=button onclick=populateSelect(states)>Click me1!</button>
<button type=button onclick=populateSelect(states2)>Click me2!</button>
...
var states = {
    "Select State": "",
    "Alabama": "AL",
    "Alaska": "AK",
    "Arizona": "AZ",
    "Arkansas": "AR"
}
var states2 = {
    "Select State": "",
    "Alabama2": "AL2",
    "Alaska2": "AK2",
    "Arizona2": "AZ2",
    "Arkansas2": "AR2"
}
function populateSelect(array) {
var vl, txt;
    for (txt in array) {
        vl = array[txt]
        $('<option/>').val(vl).text(txt).appendTo($('#selector'))
        }
}

所以它的内容取决于我点击的按钮。但是 .appendTo() 将数据添加到下拉列表的末尾,因此不会被替换。我想在添加新数据之前删除 <select> 内容。

我该怎么做?

只需在附加之前显式清空选择器:

$("#selector").empty();

for (txt in array) {
    vl = array[txt];
    $('<option/>').val(vl).text(txt).appendTo($('#selector'));
}