添加optgroups以动态选择使用javascript [英] Adding optgroups to select using javascript dynamically

查看:82
本文介绍了添加optgroups以动态选择使用javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dynamically populated (by ajax) select box with resulting options like that:

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

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

... there are actually more of them but not the essence

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

The thing i want is to group each this two option portions by optgroup using Javascript (using Jquery or Mootools maybe) after the list is loaded, so that before each of this group - we add an optgroup tag with label that we get from second option html of the group (actually the word before dash):

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

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

Though,there are always two destinations in each group.

请建议如何实现这个
提前谢谢。

Please, advice how to implement this Thanks in advance.

推荐答案

你可以这样做使用jQuery的地方:

You can do this in place using 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标记为什么。

This code iterates over all the options in the select tag, and wraps every set of two in an optgroup. It also figures out what to label the optgroup as, based on text in the options.

这篇关于添加optgroups以动态选择使用javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆