如何从选择框中删除项目或向其中添加项目?我正在运行jQuery,这应该使任务更容易。下面是一个示例选择框。

<select name="selectBox" id="selectBox">
    <option value="option1">option1</option>
    <option value="option2">option2</option>
    <option value="option3">option3</option>
    <option value="option4">option4</option>    
</select>

当前回答

window.onload = function ()
{   
    var select = document.getElementById('selectBox');
    var delButton = document.getElementById('delete');

    function remove()
    {
        value = select.selectedIndex;
        select.removeChild(select[value]);
    }

    delButton.onclick = remove;    
}

要添加项目,我将创建第二个选择框,并:

var select2 = document.getElementById('selectBox2');
var addSelect = document.getElementById('addSelect');

function add()
{
    value1 = select2.selectedIndex;
    select.appendChild(select2[value1]);    
}

addSelect.onclick = add;

但不是jQuery。

其他回答

JavaScript

function removeOptionsByValue(selectBox, value) { for (var i = selectBox.length - 1; i >= 0; --i) { if (selectBox[i].value == value) { selectBox.remove(i); } } } function addOption(selectBox, text, value, selected) { selectBox.add(new Option(text, value || '', false, selected || false)); } var selectBox = document.getElementById('selectBox'); removeOptionsByValue(selectBox, 'option3'); addOption(selectBox, 'option5', 'option5', true); <select name="selectBox" id="selectBox"> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select>

jQuery

jQuery(function($) { $.fn.extend({ remove_options: function(value) { return this.each(function() { $('> option', this) .filter(function() { return this.value == value; }) .remove(); }); }, add_option: function(text, value, selected) { return this.each(function() { $(this).append(new Option(text, value || '', false, selected || false)); }); } }); }); jQuery(function($) { $('#selectBox') .remove_options('option3') .add_option('option5', 'option5', true); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="selectBox" id="selectBox"> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select>

这应该做到:

$('#selectBox').empty();

我发现有两页看起来很有用,它是为ASP编写的。Net,但同样的东西应该适用:

如何使用jQuery从下拉列表中添加/删除项目 jQuery选择器表达式

我发现jQuery的选择框操作插件对于这类事情很有用。

您可以轻松地按索引、值或正则表达式删除项。

removeOption(index/value/regex/array[, selectedOnly])

Remove an option by
- index: $("#myselect2").removeOption(0);
- value: $("#myselect").removeOption("Value");
- regular expression: $("#myselect").removeOption(/^val/i);
- array $("#myselect").removeOption(["myselect_1", "myselect_2"]);

要删除所有选项,可以执行$("#myselect"). removeoption(/./);。

你可以这样删除选定的项目:

$("#selectBox option:selected").remove();

如果你有一个列表而不是下拉列表,这是很有用的。