Skip to main content
 首页 » 编程设计

javascript之jquery-chosen 下拉列表应该在顶部获得匹配的搜索结果

2026年09月08日2soundcode

我选择了 jquery 下拉菜单,可以很好地满足我的需要。我唯一的要求是我们能否在顶部获得匹配的搜索结果(以搜索键开头的选项)。

如果我有 3 个选项 Foo、Boo、ooo,则搜索 oo。按字母顺序获取结果,如 Boo、Foo、ooo。但是,我们能得到像 ooo、Boo、Foo 这样的结果吗?

$('.chosen-select').chosen({ 
    width: "100%", 
    search_contains: true 
}); 

我不确定该插件是否对此有任何支持。请提出建议。

请您参考如下方法:

您可以像下面这样编写自定义逻辑。我在评论中添加了待售的 fiddle 。

<div id = "results"></div> 
 
 
$( document ).ready(function() { 
    var chosenValues = ["Foo", "Boo", "Ooo"]; 
    var sortedData = checkStartsWith(chosenValues, 'oo');     
        $("#results").text(sortedData) 
}); 
function checkStartsWith(chosenValues, searchTerm) { 
    var matchedData = []; 
    var unMatchedData = []; 
    for (var i = 0; i < chosenValues.length; i++) { 
        // This condition will check if searchTerm is at the beginning of data 
        if (chosenValues[i].toLowerCase().indexOf(searchTerm.toLowerCase()) == 0) { 
            matchedData.push(chosenValues[i]); 
        } 
        else { 
            unMatchedData.push(chosenValues[i]); 
        }        
    } 
     matchedData.sort(); 
     unMatchedData.sort(); 
     return (matchedData.concat(unMatchedData)); 
}