在 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/