如何在javascript中删除未选择的下拉列表项

时间:2015-11-26 17:24:21

标签: javascript

我在互联网上寻找这个问题一段时间没有成功。 我有一些水果的下拉列表。从列表中选择项目时,应从列表中删除其他项目。例如,如果选择Apple,则应删除其他水果,Apple应仅保留在列表中。 =>函数removeUnselectedOptions()不能始终如一地执行。这里的代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Remove unselected items</title>
<script>
function removeUnselectedOptions() {
    var element = document.getElementById("fruitSelect");
    var length = element.length;
    var options = element.options;
    var selected = element.value;
    console.log(selected);
    console.log(length);
    var i = 0;
    do{
        console.log(i);
        console.log(options[i].value);
        console.log(selected);

        if(options[i].value != selected) {
            element.remove(i);
}
        i++;
   } while (i<length);
}
</script>
</head>

<body>
<form>

<br>
<select id="fruitSelect" size="5" onchange='removeUnselectedOptions();'>
    <option selected value="Select a fruit" >Select a fruit</option>
    <option>Apple</option>
    <option>Pear</option>
    <option>Banana</option>
    <option>Orange</option>
    </select>
    </form>
<br>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您可以将代码缩减为以下内容,以获取所选元素的索引,然后向后循环以将其删除。为什么倒退?因为如果你向前循环(就像你通常那样),当你删除一个元素时,索引就会改变,并且最终会留下你可能注意到的选项。

&#13;
&#13;
function removeUnselectedOptions() {
    var element = document.getElementById("fruitSelect");
    var selected = element.selectedIndex;
    for (var i = element.length-1; i >= 0; i--) {
        if (i != selected) element[i].remove()
    }
}
&#13;
<form>
    <br>
    <select id="fruitSelect" size="5" onchange='removeUnselectedOptions();'>
        <option selected value="Select a fruit">Select a fruit</option>
        <option>Apple</option>
        <option>Pear</option>
        <option>Banana</option>
        <option>Orange</option>
    </select>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

其他方式是:

function removeUnselectedOptions(){
    var element = document.getElementById("fruitSelect");
    var options = element.options;
    var i = 0;
    while (i < element.length){
        if(options[i].selected) {
            element.innerHTML = '<option value="'+options[i].label+'">'+
                options[i].label+
                '</option>';
            break;
        }
        i++;
    }
}

jsfiddle example