如何用 mark.js 突出显示不同的搜索结果?

How to highlight different search results with mark.js?

我的目标

我在 HTML 页面中有一个文本,我希望能够在上面使用两个不同的搜索框,使用 mark.js。第一个搜索框应以一种颜色突出显示匹配词,第二个搜索框应以不同颜色突出显示匹配结果。

我试过的

我有以下代码:

CSS :

mark {
  padding: 0;
  background-color:yellow;
}

jQuery :

$(function() {
  var mark = function() {
    // Read the keyword
    var keyword = $("input[name='keyword']").val();
    // Remove previous marked elements and mark
    // the new keyword inside the context
    $(".context").unmark({
      done: function() {
        $(".context").mark(keyword);
      }
    });
  };
  $("input[name='keyword']").on("input", mark);
});

HTML :

<input type="text" name="keyword">
<div class="context">
The fox went over the fence
</div>

正在工作的 JSFiddle:JSFiddle

我的问题是我不知道如何在不复制 JavaScript 代码的情况下添加第二个搜索框;当我这样做时,第二个搜索框中的搜索删除了第一个搜索框中搜索的突出显示。

我发现以下线程似乎可以解决我的问题(我不得不删除这个 link 因为我没有足够的代表 post 超过两个 link ),但是当我尝试访问 JSFiddles 时出现 404 错误。

我如何添加第二个搜索框,使第一个搜索框的结果显示为一种颜色,第二个搜索框的结果显示为另一种颜色,而不用一个搜索擦除另一个搜索框?

编辑

从我得到的答案来看,我相信我没有问清楚我的问题。所以这里有一个"half working" JSFiddle,在这里可以看到我需要的两个搜索框。如果我在第一个搜索框中搜索 'fox',然后在第二个搜索框中搜索 'fence'; 'fox' 不再突出显示,但 'fence' 突出显示。我希望两者都以不同的颜色突出显示。我真的不知道该怎么做。

只需将其添加到您的选择器中即可:

https://jsfiddle.net/1at87fnu/49/

  $(function() {
    var mark = function() {
      // Read the keyword
      var keyword = $("input[name='keyword']").val();
      // Remove previous marked elements and mark
      // the new keyword inside the context
      $(".context, .context2").unmark({
        done: function() {
          $(".context, .context2").mark(keyword);
        }
      });
    };
    $("input[name='keyword']").on("input", mark);
  });

html

<input type="text" name="keyword">
<div class="context">
    The fox went over the fence
</div>
<div class="context2">
    The fox went over the fence
</div>

感谢 jQuery 递归选择器,您可以添加所有您想要的选择器,用逗号分隔:

$('.one, #two, three[disabled]')

以此类推

更新

使用 CSS,您可以在框之间应用不同的颜色。只需瞄准您正在使用的框,就像这样 CSS:

https://jsfiddle.net/1at87fnu/50/

mark {
  padding: 0;
  background-color:yellow;
}
.context2 mark {
  padding: 0;
  background-color: orange;
}

我之前的回答是两箱一输入,这次的回答是一箱两输入,按你的要求。如果有人需要那个解决方案,我不会删除以前的答案

这个新的解决方案需要一个类名,我称之为 .secondary。见代码:

https://jsfiddle.net/1at87fnu/55/

$(function() {
  var mark = function() {
    // Read the keyword
    var keyword = $("input[name='keyword']").val();
    var keyword2 = $("input[name='keyword2']").val();
    // Remove previous marked elements and mark
    // the new keyword inside the context
    $(".context").unmark({
      done: function() {
        $(".context").mark(keyword).mark(keyword2, {className: 'secondary'});
      }
    });
  };
  $("input[name^='keyword']").on("input", mark);
});

和 CSS

mark {
  padding: 0;
  background-color:yellow;
}
mark.secondary {
  padding: 0;
  background-color: orange;
}

你可以看到我在 javascript 上调用了两次 mark() 函数,在第二次调用时我添加了一个类名。您可以在此处查看 mark.js 的更多选项:

https://markjs.io/#mark

这是最终结果的截图: