javascript - 在 Javascript 中,如何将新选项添加​​到 Html Select 中,根据文本的字母顺序值插入

标签 javascript html select

在 Javascript 中,如何将新选项添加​​到 Html Select 中,以便根据文本的字母值插入?

所以我有这个

var selectMask = document.getElementById("filenamemasks");
var newmask = document.createElement("option");
newmask.text  = maskName;
newmask.value = maskMask;
selectMask.add(newmask);

但我希望它添加新掩码,因此它紧接在按字母顺序排列之前具有文本值的选项之后。

最佳答案

您必须获取所有选项并将主题添加到名为 options 的数组变量中。其次,将新项目添加到 options 数组中,并对数组进行排序并清除选择标签,最后添加排序的 options 来选择标签,如下所示。

      
document.getElementById('button').addEventListener('click',function(event){
        var options = [];
        var selectMask = document.getElementById("filenamemasks");
        var newmask = document.createElement("option");
        newmask.text  = document.getElementById('option_title').value;
        newmask.value = document.getElementById('option_value').value;
        options.push(newmask)
        var i;
        var txt;
        for (i = 0; i < selectMask.length; i++) {
        	options.push(selectMask.options[i]);
            txt = txt + "\n" + selectMask.options[i].text;
        }
        options.sort(function(a, b) {
            var textA = a.text.toUpperCase();
            var textB = b.text.toUpperCase();
            return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
        });
        
        selectMask.innerHtml="";
        for (i = 0; i < options.length; i++) {
            selectMask.add(options[i]);
        }
      });
        <select id="filenamemasks">
        <option value="1">Apple</option>
        <option value="2">Banana</option>
        <option value="3">Mango</option>
        <option value="4">Orange</option>
    </select>
    <input id="option_title" placeholder="title">
    <input id="option_value" placeholder="value">
    <button id="button">add item</button>

关于javascript - 在 Javascript 中,如何将新选项添加​​到 Html Select 中,根据文本的字母顺序值插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51670552/

相关文章:

javascript - Firebase - 如何将 orderBy 添加到复合查询?

javascript - 是否可以在 Chart.js 中生成圆形(圆形)雷达图?

javascript - 创建的 HTML 元素的 jQuery 选项

html - 有没有办法删除 div 但保留其元素?

javascript - 当值为空时,我的输入不想将其自身着色为红色

javascript - IE 8 添加文字阴影

javascript - requestFileSystem 在 Windows XP 上抛出 SECURITY_ERR - Chrome

excel - 如何查找具有特定字符的文件名

mysql - 当另一行满足条件且一列中具有相同值时更新行

MySQL 为其中的每个 id 获取最新的 3 行