使用jQuery动态添加optgroup
我需要动态地转换它,以便Category options任何不以item开头的内容都是optgroup,将其后的内容包装到下一个Category选项中,因此上面的内容最终看起来像:使用jQuery动态添加optgroup,jquery,list,Jquery,List,我需要动态地转换它,以便Category options任何不以item开头的内容都是optgroup,将其后的内容包装到下一个Category选项中,因此上面的内容最终看起来像: <select id="myElement" multiple="multiple"> <option value="1">Category Type</option> <option value="158">itemOne</option> &
<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>
如何使用jQuery迭代并更改值以达到所需的效果?您必须迭代选项元素并根据其内容对其进行分组。使用jQuery比单纯的DOM API更简单: 可以使用来匹配将成为组的图元。然后,您可以对它们进行迭代,并调用同一元素集以匹配后续选项,因为nextUntil将在遇到该集的成员时停止,即下一个应成为组的选项 从那里,您可以使用这些元素来创建它们的元素,然后调用刚刚成为组的元素。比如:
$(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();
}
});
});
您可以在。我的实现中看到结果:
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();
});
演示:我喜欢使用wrapAll-如果我事先不知道要加入哪些元素,我不确定如何使用它。我看到了一个示例,其中要添加到optgroup的项目数是固定的。非常感谢。+1这种方法对我有效,但是它只在对multiselect进行刷新后才有效-$myElement.multiselect'refresh';因此,这可能会为其他人节省半天的时间。解决方法:参考AJS.$select2-example.append;AJS.$opt-gr1.附加“测试”;AJS.$opt-gr1.附加“test2”;
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();
});
$(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);
}
});
});
$.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);
});