9

我有一个动态填充的(通过 ajax)选择框,其中包含如下结果选项:

<select id="destination" name="destination">
<option value="london-paris">London-Paris</option>
<option value="paris-london">Paris-London</option>

<option value="london-newyork">London-New-York</option>
<option value="newyork-london">New-York-London</option>

<option value="london-berlin">London-Berlin</option>
<option value="berlin-london">Berlin-London</option>

<option value="london-helsinki">London-Helsinki</option>
<option value="helsinki-london">Helsinki-London</option>

...实际上还有更多,但不是本质

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

<select id="destination" name="destination">
<optgroup label="Paris">
<option value="london-paris">London-Paris</option>
<option value="paris-london">Paris-London</option>
</optgroup>
<optgroup label="New-York">
<option value="london-newyork">London-New-York</option>
<option value="newyork-london">New-York-London</option>
</optgroup>
<optgroup label="Berlin">
<option value="london-berlin">London-Berlin</option>
<option value="berlin-london">Berlin-London</option>
</optgroup>
<optgroup label="Helsinki">
<option value="london-helsinki">London-Helsinki</option>
<option value="helsinki-london">Helsinki-London</option>
</optgroup>
</select>

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

请提前告知如何实施此感谢。

4

2 回答 2

8

您可以使用 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/>');
            optgroup.attr('label', label);
            opt2.add(opt1).wrapAll(optgroup);
        }

    });
});

此代码遍历 select 标记中的所有选项,并将每两个选项的集合包装在一个 optgroup 中。它还根据选项中的文本确定将 optgroup 标记为什么。

于 2010-02-04T23:29:47.400 回答
5

这不是太棘手,您只需要稍微调整一下您的选项。将它们从文档流中取出,在两个相关选项的位置添加一个 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]);
}
于 2010-02-04T23:15:37.820 回答