根据我的研究,在进行选择时没有直接的方法来收集 optgroup id。这是生成的 HTML:
<select class="js-example-data-array select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<optgroup label="enhancement">
<option value="c5">enhancement child1</option>
<option value="c6">enhancement child2</option>
</optgroup>
<option value="c1">bug</option>
<option value="c2">duplicate</option>
<option value="c3">invalid</option>
<option value="c4">wontfix</option>
</select>
编辑
经过进一步检查,html body.forceShow select.js-example-data-array.select2-hidden-accessible optgroup 的 DOM 确实有 value 和 p0。仍在尝试根据具体选择找出如何收集此信息。
您可以将此详细信息添加到数据中,然后您可以将其取出。示例:https://jsfiddle.net/Twisty/rfn5p18x/4/
HTML
<select class="js-example-data-array">
</select>
<select class="js-example-data-array-selected">
<option value="2" selected="selected">duplicate</option>
</select>
<div id="results">
</div>
JQuery
var data = [{
id: 'p0',
text: 'enhancement',
children: [{
id: 'c5',
text: 'enhancement child1',
parent: 'p0'
}, {
id: 'c6',
text: 'enhancement child2',
parent: 'p0'
}]
}, {
id: 'c1',
text: 'bug'
}, {
id: 'c2',
text: 'duplicate'
}, {
id: 'c3',
text: 'invalid'
}, {
id: 'c4',
text: 'wontfix'
}];
$(document).ready(function() {
$(".js-example-data-array").select2({
data: data
});
$(".js-example-data-array").on("select2:select", function(e) {
if (e.params.data.parent.length) {
console.log(e.params.data.parent + " > " + e.params.data.id + " selected");
} else {
console.log(e.params.data.id + " selected");
}
});
$(".js-example-data-array-selected").select2({
data: data
});
});
您现在可以看到数据包含对父级的引用,并且现在可以在选择选项时访问。它在.val() 下不可用,但您可以在选择时将其存放在其他地方,或修改.val() 以包含它。
编辑已修复
能够从$("option:selected").parent("optgroup").val(); 收集optgroup id。工作示例:https://jsfiddle.net/Twisty/rfn5p18x/7/
JQuery
var data = [{
id: 'p0',
text: 'enhancement',
children: [{
id: 'c5',
text: 'enhancement child1',
}, {
id: 'c6',
text: 'enhancement child2',
}]
}, {
id: 'c1',
text: 'bug'
}, {
id: 'c2',
text: 'duplicate'
}, {
id: 'c3',
text: 'invalid'
}, {
id: 'c4',
text: 'wontfix'
}];
$(document).ready(function() {
$(".js-example-data-array").select2({
data: data
});
$(".js-example-data-array").on("select2:select", function(e) {
var pID = $("option:selected").parent("optgroup").val();
if (typeof pID !== "undefined") {
$("#results").append("Parent: " + pID + "<br />\r\n");
}
$("#results").append("Value: " + $(this).val() + "<br />\r\n");
});
$(".js-example-data-array-selected").select2({
data: data
});
});