2014-02-24 162 views

回答

18

居然发现解决方案通过修改匹配选择

$("#myselect").select2({ 
    matcher: function(term, text, opt){ 
     return text.toUpperCase().indexOf(term.toUpperCase())>=0 || opt.parent("optgroup").attr("label").toUpperCase().indexOf(term.toUpperCase())>=0 
    } 
}); 

的前提下,该标签属性已在各OPTGROUP设置。

+0

不错!谢谢。 – flu

+0

谢谢,那真是超级有用! – Dave

+1

不错!不过,我建议使用默认的匹配器实现,除非你故意偏离默认的匹配器。 'element.select2({matcher:function(term,text,opt){return element.select2.defaults.matcher(term,text)|| element.select2.defaults.matcher(term,opt.parent(“optgroup”)) .attr(“label”));}});'这可以通过不仅忽略大小写而且忽略变音符号来实现更好的匹配。 – hvd

0

的人一些小的改动建议代码,少重复,当没有父optgroups科佩斯:

$('select').select2({ 
    matcher: function(term, text, opt){ 
     var matcher = opt.parent('select').select2.defaults.matcher;       
     return matcher(term, text) || (opt.parent('optgroup').length && matcher(term, opt.parent('optgroup').attr("label"))); 
    } 
}); 
10

以上答案似乎不选择二4.0,所以如果你的工作开箱“再狩猎的是,检查了这一点:https://github.com/select2/select2/issues/3034

(使用这样的功能:$("#example").select2({matcher: modelMatcher});

function modelMatcher (params, data) { 
    data.parentText = data.parentText || ""; 

    // Always return the object if there is nothing to compare 
    if ($.trim(params.term) === '') { 
    return data; 
    } 

    // Do a recursive check for options with children 
    if (data.children && data.children.length > 0) { 
    // Clone the data object if there are children 
    // This is required as we modify the object to remove any non-matches 
    var match = $.extend(true, {}, data); 

    // Check each child of the option 
    for (var c = data.children.length - 1; c >= 0; c--) { 
     var child = data.children[c]; 
     child.parentText += data.parentText + " " + data.text; 

     var matches = modelMatcher(params, child); 

     // If there wasn't a match, remove the object in the array 
     if (matches == null) { 
     match.children.splice(c, 1); 
     } 
    } 

    // If any children matched, return the new object 
    if (match.children.length > 0) { 
     return match; 
    } 

    // If there were no matching children, check just the plain object 
    return modelMatcher(params, match); 
    } 

    // If the typed-in term matches the text of this term, or the text from any 
    // parent term, then it's a match. 
    var original = (data.parentText + ' ' + data.text).toUpperCase(); 
    var term = params.term.toUpperCase(); 


    // Check if the text contains the term 
    if (original.indexOf(term) > -1) { 
    return data; 
    } 

    // If it doesn't contain the term, don't return anything 
    return null; 
} 
+0

这工作。这现在应该是答案,因为上述确实有问题。感谢willbradley。 – bubjavier