1
我有一個jQuery腳本,它使用簡單的文本輸入來搜索字符串。如果它找到字符串,它只會高亮顯示字符串本身。我所有的數據都在一個表內,所以我想知道如果在行的任何位置找到字符串,是否可以突出顯示整行?如何在搜索時突出顯示錶格行而不是僅顯示文本?
這個js小提琴有一個工作演示: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);
one .parent()就足夠了。 – Slugge
不是真的,它只會選擇列而不是行。 – Hatsjoem
這個伎倆!非常感謝,感謝您的幫助! –