使用 jQuery 动态添加 optgroups

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12561680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:49:00  来源:igfitidea点击:

Adding optgroups dynamically using jQuery

jquerylist

提问by key2starz

<select id="myElement" multiple="multiple">
  <option value="1">Category Type</option>
  <option value="158">itemOne</option>
  <option value="157">itemTwo</option>
  <option value="7">My Type</option>
  <option value="20">itemThree</option>
  <option value="21">itemFour</option>
  <option value="22">itemFive</option>
  <option value="8">Category Yet Another</option>
  <option value="31">itemCheese</option>
  <option value="32">itemBrain</option>
</select>

I need to dynamically convert this so that "Category" options (anything that doesn't start with "item") is an optgroup, wrapping whaterver comes after it until the next Category option, so the above would end up looking like:

我需要动态转换它,以便“类别”选项(任何不以“项目”开头的内容)是一个 optgroup,将它后面的任何内容包装起来,直到下一个类别选项,因此上面的内容最终看起来像:

<select id="myElement" multiple="multiple">
  <optGroup label="Category Type">
    <option value="158">One</option>
    <option value="157">Two</option>
  </optGroup>
  <optGroup label="My Type">
    <option value="20">Three</option>
    <option value="21">Four</option>
    <option value="22">Five</option>
  </optGroup>
  <optGroup label="Category Yet Another">
    <option value="31">Cheese</option>
    <option value="32">Brain</option>
  </optGroup>
</select>

How can I iterate over this and change values to acheive the desired effect using jQuery?

我如何迭代这个并更改值以使用 jQuery 实现所需的效果?

回答by Micha? Miszczyszyn

You have to iterate over the optionelements and group them based on their contents. Using jQuery makes it way easier than just pure DOM API:

您必须遍历option元素并根据其内容对它们进行分组。使用 jQuery 使它比纯 DOM API 更容易:

http://jsfiddle.net/kpykoahe/2/

http://jsfiddle.net/kpykoahe/2/

$(document).ready(() => {
    const $cont = $('select');
    $('option').each((idx, el) => {
        const $el = $(el);
        if ($el.text().startsWith('item')) {
            $cont.find('optgroup').last().append($el);
            $el.text($el.text().substr(4));
        } else {
            $('<optgroup/>').attr('label', $el.text()).appendTo($cont);
            $el.remove();
        }
    });
});

回答by Frédéric Hamidi

You can use filter()to match the <option>elements that will become groups. Then, you can iterate over them and call nextUntil()on the same element set to match the subsequent options (as nextUntil()will stop when it encounters a member of the set, i.e. the next option that should become a group).

您可以使用filter()来匹配<option>将成为组的元素。然后,您可以迭代它们并在相同的元素集上调用nextUntil()以匹配后续选项(nextUntil()当它遇到集合的成员时将停止,即应该成为组的下一个选项)。

From there, you can use wrapAll()on these <option>elements to create their <optgroup>element, then call remove()on the <option>element that just became a group. Something like:

从那里,您可以在这些元素上使用wrapAll()<option>来创建它们的<optgroup>元素,然后在刚刚成为组的元素上调用remove()<option>。就像是:

var $groups = $("#myElement option").filter(function() {
    return $(this).text().indexOf("item") != 0;
});
$groups.each(function() {
    var $this = $(this);
    $this.nextUntil($groups).wrapAll($("<optgroup>", {
        label: $this.text()
    })).end().remove();
});

You can see the results in this fiddle.

你可以在这个 fiddle 中看到结果。

回答by webdeveloper

My implementation:

我的实现:

$(function(){
    var target = $('#target'),
        optGroup;

    function strStartsWith(str, prefix) {
        return str.indexOf(prefix) === 0;
    }

    $('#myElement').find('option').each(function(){
        var elm = $(this).clone();
        if(strStartsWith(elm.text(), 'item'))
        {
            elm.text(elm.text().substr(4));
            if(optGroup) optGroup.append(elm);
        }
        else
        {
            optGroup = $('<optgroup>').attr('label', elm.text());
            target.append(optGroup);
        }
    });
});

Demo: http://jsfiddle.net/HUHRz/1/

演示:http: //jsfiddle.net/HUHRz/1/

回答by Parth Desai

$.each(data, function () {

    if (prevGroupName.indexOf(this.Group.Name) == -1) {
        $prevGroup = $('<optgroup />').prop('label', this.Group.Name).appendTo('#ConfigurationId');
    } else {
        $prevGroup = $("optgroup[label='" + this.Group.Name + "']");
    }
    $("<option />").val(this.Value).text(this.Text).appendTo($prevGroup);
    prevGroupName.push(this.Group.Name);
});