jQuery 搜索和突出显示,2 种颜色 - 2 个列表

jQuery Search and Hightlight, 2 Colors - 2 Lists

我有一些旧代码可用于突出显示单词列表:

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

$(document).ready(function(){   
 $("td").highlight("car")
 $("td").highlight("sales");
 $("td").highlight("income");
});

</script>;

与此非常相似post:Search and Highlight in jQuery

但现在我需要相同的脚本来突出显示同一页面上具有不同颜色的第二个列表。我要求的与此非常相似 post: Using multiple colors for highlighting

好像看不懂

(根据 OP 的反馈更新了答案...)

最快的解决方案是修改现有函数,使其接受第二个参数,指定要添加到突出显示范围的 CSS 类名。

(或者更具体地说,在我下面的示例中,不是整个 CSS className,而是颜色部分。这会自动附加到词干 "highlight-" 中,这样您就不必输入整个每次调用该函数时都会发生的事情。)

所以...

// 1. Change: jQuery.fn.highlight = function(pat) {
// to...
jQuery.fn.highlight = function(pat, color) {

// 2. Change: spannode.className = 'highlight';
// to...
spannode.className = 'highlight-'+color;

您的函数现在接受名为 'color' 的第二个参数,并且 spannode.className 根据指定的颜色是动态的。

// 3. Add some classes like these to your CSS...
//
.highlight-red {background-color:red;}
.highlight-green {background-color:green;}
.highlight-pink {color:white;font-weight:bold; background-color:pink;}

// 4. Then call your function like this...
//
$("td").highlight("car", 'red')
$("td").highlight("sales", 'green');
$("td").highlight("income", 'pink');

演示:运行 它在 JSFiddle...