我有一个jQuery脚本,它使用简单的文本输入来搜索字符串。如果找到字符串,则仅突出显示字符串本身。我的所有数据都在一个表格中,所以我想知道如果在行中的任何地方找到字符串,是否可以突出显示整行?
这个JS Fiddle有一个工作演示:http://jsfiddle.net/s8fTA/
此脚本使用搜索字符串,但调用下面的突出显示脚本:
$(function() {
var search = $('.beer-search'),
content = $('.beer-list'),
matches = $(), index = 0;
// Listen for the text input event
search.on('input', function(e) {
// Only search for strings 2 characters or more
if (search.val().length >= 2) {
// Use the highlight plugin
content.highlight(search.val(), function(found) {
});
}
else {
content.highlightRestore();
}
});
});
突出显示脚本: (函数($){
var termPattern;
$.fn.highlight = function(term, callback) {
return this.each(function() {
var elem = $(this);
if (!elem.data('highlight-original')) {
// Save the original element content
elem.data('highlight-original', elem.html());
} else {
// restore the original content
elem.highlightRestore();
}
termPattern = new RegExp('(' + term + ')', 'ig');
// Search the element's contents
walk(elem);
// Trigger the callback
callback && callback(elem.find('.match'));
});
};
$.fn.highlightRestore = function() {
return this.each(function() {
var elem = $(this);
elem.html(elem.data('highlight-original'));
});
};
function walk(elem) {
elem.contents().each(function() {
if (this.nodeType == 3) { // text node
if (termPattern.test(this.nodeValue)) {
$(this).replaceWith(this.nodeValue.replace(termPattern, '<span class="match">$1</span>'));
}
} else {
walk($(this));
}
});
}
})(jQuery);
答案 0 :(得分:6)
选择找到文本的行:
content.highlight(search.val(), function(found) {
// like this - first parent to select the column (td) - second parent to select the row (tr)
found.parent().parent().css('background','yellow');
// or like this - finds the closest row (tr)
found.closest('tr').css('background','yellow');
});