gpt4 book ai didi

javascript - 搜索时如何突出显示表格行而不仅仅是文本?

转载 作者:行者123 更新时间:2023-11-28 04:56:01 25 4
gpt4 key购买 nike

我有一个 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);

最佳答案

选择文本所在的行:

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');
});

FIDDLE DEMO

关于javascript - 搜索时如何突出显示表格行而不仅仅是文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23090753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com