添加optgroups以动态选择使用javascript

我有一个动态填充(由ajax)选择框,其结果选项如下:

 London-Paris Paris-London London-New-York New-York-London London-Berlin Berlin-London London-Helsinki Helsinki-London 

……实际上有更多但不是本质

我想要的是在加载列表之后使用Javascript(可能使用Jquery或Mootools)将每个这两个选项部分分组,以便在每个组之前 – 我们添加一个带有我们从第二个选项获得的标签的optgroup标签组的html(实际上是破折号之前的单词):

   London-Paris Paris-London   London-New-York New-York-London   London-Berlin Berlin-London   London-Helsinki Helsinki-London   

但是,每组中总有两个目的地。

请提前告知如何实施此项。

你可以使用jQuery来做到这一点:

 $(document).ready(function() { var select = $('#destination'); var opt1, opt2; $('option', select).each(function(i) { if (i % 2 === 0) { opt1 = $(this); } else { opt2 = $(this); var label = opt1.text().replace('London-', ''); var optgroup = $(''); optgroup.attr('label', label); opt2.add(opt1).wrapAll(optgroup); } }); }); 

此代码迭代select标记中的所有选项,并将每组两个包装在optgroup中。 它还根据选项中的文本计算出将optgroup标记为什么。

这不是太棘手,你只需要稍微调整一下你的选择。 将它们从文档流中取出,在两个相关选项的位置添加一个optgroup,并将选项附加到该optgroup。

假设选项实际上是顺序的,如在您的示例中,可能的,良好的旧DOM脚本实现如下:

 var destinationSelect = document.getElementById("destination"); var options = destinationSelect.getElementsByTagName("option"); var optgroups = []; while(options.length > 0) { var option1 = options[0]; var option2 = options[1]; var optgroup = document.createElement("optgroup"); var label = option1.innerHTML.replace(/^[^\-]-/, ""); optgroup.setAttribute("label", label); destinationSelect.removeChild(option1); destinationSelect.removeChild(option2); optgroup.appendChild(option1); optgroup.appendChild(option2); optgroups.push(optgroup); } for(var i = 0; i < optgroups.length; i ++) { destinationSelect.appendChild(optgroups[i]); }