如何对 jQuery 自动完成的结果设置限制?
这是我的代码:
$.ajax({
url: "/cache/search/SearchModels.xml",
dataType: "xml",
success: function(xmlResponse) {
var data = $("SearchModel", xmlResponse).map(function() {
return {
value: $("Name", this).text() + ", " + $("Description", this).text(),
id: $("No", this).text(),
name: $("Name", this).text(),
url: $("URL", this).text()
};
}).get();
$("#txtTopSearch").autocomplete({
source: data,
minLength: 2,
select: function(event, ui) {
BlockUI();
if (typeof (ui.item.url) != 'undefined') {
window.location = ui.item.url;
}
else {
alert('Page not found!');
$.unblockUI();
}
},
search: function(event, ui) {
$('#txtTopSearch').addClass('searchInProgress');
},
close: function(event, ui) {
$('#txtTopSearch').removeClass('searchInProgress');
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><span style='font-size:.9em; font-weight:bold;'>" + item.id + "</span><br /><span style='font-size:.8em;'>" + item.name + "</span></a>")
.appendTo(ul);
};
},
error: function(xhr, textStatus, errorThrown) {
alert('Error: ' + xhr.statusText);
}
});
此代码返回查询中的所有结果,但我想将其限制为仅显示 10 个结果。在旧的自动完成版本中有一个选项,但现在已弃用。
XML 示例:
<?xml version="1.0"?>
<ArrayOfSearchModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SearchModel>
<No>1</No>
<Name>My product</Name>
<Description>My description</Description>
<Tags>blue;brown;</Tags>
<URL>/Products/1</URL>
</SearchModel>
</ArrayOfSearchModel>
最佳答案
最终更新
了解在我之前的答案中我限制了整个 xml 结果集而不是自动完成的结果
由于您已覆盖默认的 _renderItem
方法,因此您可以覆盖默认的 _renderMenu
。
$.ui.autocomplete.prototype._renderMenu = function( ul, items ) {
var self = this;
$.each( items, function( index, item ) {
if (index < 10) // here we define how many results to show
{self._renderItem( ul, item );}
});
}
答案修改自此jQueryUI: how can I custom-format the Autocomplete plug-in results?所以感谢@cheeso..
<小时/>原始答案
在您成功
回调中使用$("SearchModel:lt(10)", xmlResponse).map(...
:lt(10)
获取索引小于 10 的元素。因此最多将返回 10 个结果。
(当然数字 10 可以是任何你想要的)
查看 http://api.jquery.com/lt-selector/ 处的 :lt()
选择器
更新
虽然我无法理解为什么第一个答案不起作用,因为 SearchModel
是一个标签,我们的目标是..我们可以在 map 方法中移动过滤..
success: function(xmlResponse) {
var data = $("SearchModel", xmlResponse).map(function(index) {
if (index<10)
{
return {
value: $("Name", this).text() + ", " + $("Description", this).text(),
id: $("No", this).text(),
name: $("Name", this).text(),
url: $("URL", this).text()
};
}
else
{ return null; }
}).get();
关于jquery - 限制 jQuery 自动完成中的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4071887/