如何自定义自动完成插件结果的格式?
-
19-09-2019 - |
题
我正在使用 jQuery UI 自动完成插件. 。有没有办法在下拉结果中突出显示搜索字符序列?
例如,如果我有“foo bar”作为数据并且我输入“foo”,我会得到“富 下拉菜单中的“bar”,如下所示:
解决方案
是的,如果你给自动完成打猴子补丁就可以。
在 jQuery UI v1.8rc3 中包含的自动完成小部件中,建议弹出窗口是在自动完成小部件的 _renderMenu 函数中创建的。这个函数的定义如下:
_renderMenu: function( ul, items ) {
var self = this;
$.each( items, function( index, item ) {
self._renderItem( ul, item );
});
},
_renderItem 函数定义如下:
_renderItem: function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
},
因此,您需要做的是将 _renderItem fn 替换为您自己的创建内容,以产生所需的效果。我开始学习的这种重新定义库中内部函数的技术称为 猴子补丁. 。我是这样做的:
function monkeyPatchAutocomplete() {
// don't really need this, but in case I did, I could store it and chain
var oldFn = $.ui.autocomplete.prototype._renderItem;
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
var re = new RegExp("^" + this.term) ;
var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" +
this.term +
"</span>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
}
调用该函数一次 $(document).ready(...)
.
现在,这是一个黑客行为,因为:
为列表中呈现的每个项目创建一个正则表达式 obj。该正则表达式 obj 应该重新用于所有项目。
没有用于格式化已完成部分的 CSS 类。这是一种内联样式。
这意味着如果同一页面上有多个自动完成功能,它们都会得到相同的处理。css 样式可以解决这个问题。
...但它说明了主要技术,并且它适用于您的基本要求。
更新的工作示例: http://output.jsbin.com/qixaxinuhe
要保留匹配字符串的大小写,而不是使用键入字符的大小写,请使用以下行:
var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" +
"$&" +
"</span>");
也就是说,从上面的原始代码开始,只需替换 this.term
和 "$&"
.
编辑
上述变化 每一个 页面上的自动完成小部件。如果您只想更改一个,请参阅以下问题:
如何修补页面上“仅一个”自动完成实例?
其他提示
这也适用:
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
的@ JORN Zaefferer和@ Cheeso的响应的组合。
超级有帮助的。谢谢。 1。
下面是排序上的光版本“字符串必须与术语开始”:
function hackAutocomplete(){
$.extend($.ui.autocomplete, {
filter: function(array, term){
var matcher = new RegExp("^" + term, "i");
return $.grep(array, function(value){
return matcher.test(value.label || value.value || value);
});
}
});
}
hackAutocomplete();
jQueryUI的1.9.0改变_renderItem如何工作的。
下面的代码采用这种变化考虑在内,也显示了如何在做使用JORN Zaefferer的jQuery的自动完成插件突出匹配。这将突出在整体搜索词的所有个别条款。
由于移动到使用基因敲除和jqAuto我发现这个造型的结果的更容易的方法。
function monkeyPatchAutocomplete() {
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
// Escape any regex syntax inside this.term
var cleanTerm = this.term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
// Build pipe separated string of terms to highlight
var keywords = $.trim(cleanTerm).replace(' ', ' ').split(' ').join('|');
// Get the new label text to use with matched terms wrapped
// in a span tag with a class to do the highlighting
var re = new RegExp("(" + keywords + ")", "gi");
var output = item.label.replace(re,
'<span class="ui-menu-item-highlight">$1</span>');
return $("<li>")
.append($("<a>").html(output))
.appendTo(ul);
};
};
$(function () {
monkeyPatchAutocomplete();
});
下面不言而喻,功能完整的例子:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Autocomplete - jQuery</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label for="search"></label>
<input type="text" name="search" id="search" />
</form>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
$(function(){
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
var availableTags = [
"JavaScript",
"ActionScript",
"C++",
"Delphi",
"Cobol",
"Java",
"Ruby",
"Python",
"Perl",
"Groove",
"Lisp",
"Pascal",
"Assembly",
"Cliper",
];
$('#search').autocomplete({
source: availableTags,
minLength: 3
});
});
</script>
</body>
</html>
希望这有助于
有一个更简单的方法,试试这个:
$('ul: li: a[class=ui-corner-all]').each (function (){
//grab each text value
var text1 = $(this).text();
//grab user input from the search box
var val = $('#s').val()
//convert
re = new RegExp(val, "ig")
//match with the converted value
matchNew = text1.match(re);
//Find the reg expression, replace it with blue coloring/
text = text1.replace(matchNew, ("<span style='font-weight:bold;color:green;'>") + matchNew + ("</span>"));
$(this).html(text)
});
}
以下是 Ted de Koning 解决方案的重述。这包括 :
- 不区分大小写的搜索
- 查找搜索字符串多次出现的情况
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var sNeedle = item.label;
var iTermLength = this.term.length;
var tStrPos = new Array(); //Positions of this.term in string
var iPointer = 0;
var sOutput = '';
//Change style here
var sPrefix = '<strong style="color:#3399FF">';
var sSuffix = '</strong>';
//Find all occurences positions
tTemp = item.label.toLowerCase().split(this.term.toLowerCase());
var CharCount = 0;
tTemp[-1] = '';
for(i=0;i<tTemp.length;i++){
CharCount += tTemp[i-1].length;
tStrPos[i] = CharCount + (i * iTermLength) + tTemp[i].length
}
//Apply style
i=0;
if(tStrPos.length > 0){
while(iPointer < sNeedle.length){
if(i<=tStrPos.length){
//Needle
if(iPointer == tStrPos[i]){
sOutput += sPrefix + sNeedle.substring(iPointer, iPointer + iTermLength) + sSuffix;
iPointer += iTermLength;
i++;
}
else{
sOutput += sNeedle.substring(iPointer, tStrPos[i]);
iPointer = tStrPos[i];
}
}
}
}
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + sOutput + "</a>")
.appendTo(ul);
};
下面是一种不需要任何正则表达式和多个结果中的标签匹配的版本。
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var highlighted = item.label.split(this.term).join('<strong>' + this.term + '</strong>');
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + highlighted + "</a>")
.appendTo(ul);
};
看一看组合框的演示,它包括结果高亮: http://jqueryui.com /演示/自动填充/#组合框
在使用正则表达式那里还涉及HTML结果。
这是我的版本:
- 使用 DOM 函数而不是 RegEx 来中断字符串/注入 span 标签
- 仅影响指定的自动完成,而不是全部
- 适用于 UI 版本 1.9.x
function highlightText(text, $node) {
var searchText = $.trim(text).toLowerCase(),
currentNode = $node.get(0).firstChild,
matchIndex,
newTextNode,
newSpanNode;
while ((matchIndex = currentNode.data.toLowerCase().indexOf(searchText)) >= 0) {
newTextNode = currentNode.splitText(matchIndex);
currentNode = newTextNode.splitText(searchText.length);
newSpanNode = document.createElement("span");
newSpanNode.className = "highlight";
currentNode.parentNode.insertBefore(newSpanNode, currentNode);
newSpanNode.appendChild(newTextNode);
}
}
$("#autocomplete").autocomplete({
source: data
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var $a = $("<a></a>").text(item.label);
highlightText(this.term, $a);
return $("<li></li>").append($a).appendTo(ul);
};
可以使用如下因素的代码:
LIB:
$.widget("custom.highlightedautocomplete", $.ui.autocomplete, {
_renderItem: function (ul, item) {
var $li = $.ui.autocomplete.prototype._renderItem.call(this,ul,item);
//any manipulation with li
return $li;
}
});
和逻辑:
$('selector').highlightedautocomplete({...});
它创建定制窗口小部件可以覆盖_renderItem
而不覆盖原来的插件原型_renderItem
。
在我的例子也使用原始呈现功能的一些简化代码
这是重要的事情,如果你想在不同的地方有自动完成不同的视图中使用插件,不想破坏你的代码。
如果您而是使用第三方插件,它具有突出显示选项: http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
(参见选项标签)
要支持多个值,只需简单地添加以下功能:
function getLastTerm( term ) {
return split( term ).pop();
}
var t = String(item.value).replace(new RegExp(getLastTerm(this.term), "gi"), "<span class='ui-state-highlight'>$&</span>");