如何使用 jquery 和 select2 获取所选 optgroup 的值?

How can I get the value of selected optgroup with jquery and select2?

我使用 select2 作为 selectbox 并使 <optgroup> select 可用,但是当我 select 它时我无法获取值. 当您键入 optgroup 名称时,获取 <optgroup> 的所有选项非常重要,因此我无法将 <optgroup> 替换为常用的 <option>.


参见 jsfiddle 示例 http://jsfiddle.net/iptspl/41r158dm/1/

您可以尝试在事件上使用 choice 值(如果存在),然后检查 children,然后组合它们的值。

on("select2-selecting", function(e) {
   var value, choice = e.choice; 
   if(choice.children && choice.children.length > 0) {
        value = [];
        $(choice.children).each(function(index, child) {
            value.push($(child.element).val());
        });
        value = value.join(",");
   } else {
        value = e.val;
   } 
   alert(value);
});

无论如何,无论您做什么,您很可能需要做类似的事情,即检测它是否是 optgroup,然后遍历子项并创建值。