我正在研究JQueryUI自动完成,并希望与默认行为略有不同。我有一个字符串数组:
var json = ["Atlanta", "Chicago", "Little Rock", "RockFord", "Rhode Island"];
当我将以下内容输入自动完成时,我希望得到以下结果。
输入:“R”
实际结果:
小石城罗德岛
罗克福德
预期结果:
罗德岛
罗克福德
小石城输入:摇滚
实际结果:
小石城罗克福德
预期结果:
罗克福德
小石城这是我的jsFiddle
我希望结果按字母顺序排序,然后按匹配排序。我查看了这个link,但这只能让我按字母排序。当我输入“Rock”时,我只能获得RockFord。
有什么想法吗?
答案 0 :(得分:2)
尝试使用._renderMenu
,$.grep()
var json = ["Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Little Rock",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"RockFord",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming",
];
json.sort();
$("input").autocomplete({
source: json
}).data("ui-autocomplete")._renderMenu = function(ul, items) {
var that = this;
var val = that.element.val();
$.each($.grep(items, function(value, key) {
return new RegExp(val.toLowerCase())
.test(value.value.toLowerCase().slice(0, val.length))
}), function(index, item) {
that._renderItemData(ul, item);
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.9.2/jquery-ui.js">
</script>
<input type="text" />
jsfiddle http://jsfiddle.net/Gm9Bz/75/
另请参阅_renderMenu(ul, items)
,jQueryUI: how can I custom-format the Autocomplete plug-in results?,Override both _renderItem and _renderMenu