我通过重载 _renderItem 方法来检查 JSON 对象中用户搜索的文本,从而在 JQuery 的自动完成上进行文本匹配。找到它后,我将其替换为带有“user_highlight_match”类的 span 标签。
我正在进行多词搜索,因此“John Smi”会突出显示 John,然后是 Smi,而搜索“John James Smi”会突出显示“John”和“Smi”。问题在于,假设您搜索“John Las”,它将开始匹配 span 标签的类属性(如果它已经存在)。我该如何解决这个问题?
编辑:这里有一些代码显示了我在说什么:
renderItem = function(ul, item) {
li = $('<li>', id: item._id);
if this.term and not item.dialog
terms = this.term.split(' ');
for term in terms
re = new RegExp("("+term+")", 'i');
match = re.exec(item.name);
if match
item.name = item.name.replace re, "<span class=\"user_highlight_match\">+match[0]+</span>";
)
所以第一个术语会很好地匹配,但之后每次,如果您在 html 标签中搜索任何内容,部分匹配将被替换为标签。所以说在“las”上有一场比赛,它会变成这样:
<span c<span class="user_highlight_match">Last</span>s="user_highlight_match">Last</span>
最佳答案
您必须搜索文本节点并将它们替换为您想要的 html。看到这个问题:Find word in HTML .
编辑:这是我的答案的 jQuery 版本。
http://jsfiddle.net/gilly3/auJkG/
function searchHTML(searchString, htmlString) {
var expr = new RegExp(searchString, "gi");
var container = $("<div>").html(htmlString);
var elements = container.find("*").andSelf();
var textNodes = elements.contents().not(elements);
textNodes.each(function() {
var matches = this.nodeValue.match(expr);
if (matches) {
var parts = this.nodeValue.split(expr);
for (var n = 0; n < parts.length; n++) {
if (n) {
$("<span>").text(matches[n - 1]).insertBefore(this);
}
if (parts[n]) {
$(document.createTextNode(parts[n])).insertBefore(this);
}
}
$(this).remove();
}
});
return container.html();
}
关于javascript - 替换文本而不是 HTML 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7719955/