Javascript 如何在html中select(Multiple)的指定索引处插入选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6912831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:44:27  来源:igfitidea点击:

How to insert option at specified index of select(Multiple) in html?

javascriptjqueryhtml

提问by Dipak

How can I insert an option element at a specified index in a <select multiple>element?

如何在元素的指定索引处插入选项<select multiple>元素?

Thanks

谢谢

回答by Corneliu

$("select option").eq(index).before($("<option></option>").val(val).html(text));

回答by Carl Sharman

Vanilla javascript (no jQuery) and cross browser.

Vanilla javascript(无 jQuery)和跨浏览器。

To insert a new option into the select "mySelect", with value of "1" and text of "text", before the 0th existing item:

在第 0 个现有项目之前,将一个新选项插入到选择“mySelect”中,值为“1”,文本为“text”:

mySelect.options.add(new Option("text", "1"), mySelect.options[0]);

mySelect.options.add(new Option("text", "1"), mySelect.options[0]);

See: https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement#add%28%29

请参阅:https: //developer.mozilla.org/en/docs/Web/API/HTMLSelectElement#add%28%29

回答by Brian

And yet another option, sans jquery:

还有另一种选择,sans jquery:

Markup:

标记:

<select multiple="multiple" id="mySelect">
    <option>First</option>
    <option>Third</option>
</select>

JS:

JS:

<script type="text/javascript">
    var myDdl = document.getElementById("mySelect");
    var myOption = document.createElement("OPTION");
    myOption.innerText = "Second";

    myDdl.options.insertBefore(myOption, myDdl.options[myDdl.options.length - 1]);

</script>

回答by pizzamonster

I submit this answer because jquery was not specified in the question.

我提交此答案是因为问题中未指定 jquery。

function insertOptionToSelect(select, idx, option) {
    var saved = [];
    var i;
    for (i = 0; i < select.options.length; i++) {
        saved.push(select.options[i]);
    }
    select.options.length = 0;
    for (i = 0; i < idx; i++) {
        select.options[select.options.length] = saved[i];
    }
    select.options[select.options.length] = option;
    while (i < saved.length) {
        select.options[select.options.length] = saved[i++];
    }
}

The following will insert an option at the selected index of select with id 'MyPizzaSelect':

以下将在选定的 select 索引处插入一个选项,id 为“MyPizzaSelect”:

var myselect = document.getElementById('MyPizzaSelect');
insertOptionToSelect(myselect, myselect.selectedIndex, new Option('Pizza Margarita', '12345'));

回答by Joseph Marikle

Here's a way you can do it:

这里有一种方法可以做到:

var myOption = "<option>Dynamic Option</option>";
var index = 2;
$(myOption).insertBefore("select option:nth-child("+index+")");

fiddle example

小提琴示例