如果元素包含这些单词中的任何一个,则将该单词包装在 span 中

If element contains any of these words then wrap that word in span

如果在标题中找到某些词,我想通过将这些词包裹在一个跨度 class 中来突出显示这些词。有没有一种方法可以编写要检查的单词列表,然后使用相同的命令用范围 class?

包装这些单词中的任何一个

例如:

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>

检查这三个元素中的每一个(但会有 20 个左右)的词 Balloon 或 Oranges,然后将这些词用 span 颜色包裹起来。

我可以使用:

$('h1').html($('h1').html().replace(/(balloon)/g,'<span class="red">balloon</span>'));

但我必须为每个单词编写该查询,而如果可能的话,我想要更简单的东西。

你可以有一个包含所有你想要包装的词的对象(包括另一个规范,例如 class 或使用的标签),然后在使用你的命令构造要使用的字符串。

您可以保留一个单词数组,然后迭代并替换每个单词中的单词header

var words = [
    "balloon",
    "either"
];

$('h1').html(function(_,html) {
    var reg = new RegExp('('+words.join('|')+')','gi');
    return html.replace(reg, '<span class="red"></span>', html)
});
.red {color : red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>

像这样遍历你的元素集,并将其替换为关键字数组中的任何内容:

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>
<h1>This title contains both Balloon and Oranges</h1>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script>
var wordsToHighlight = ['Balloon', 'Oranges'];
$('h1').each(function() {
  for (var i = 0, l = wordsToHighlight.length; i < l; i++) {
    if ($(this).html().indexOf(wordsToHighlight[i]) !== -1) {
      var newValue = $(this).html().replace(wordsToHighlight[i], 
          '<span>' + wordsToHighlight[i] + '</span>');
      $(this).html(newValue);
    }
  }
});
</script>

虽然这里提供的答案在理论上是正确的,但他们会使用 innerHTML 这是邪恶的。它会一遍又一遍地破坏事件并触发 DOM 生成。此外,您可能需要一次删除高光,因此您正在重新倒转轮子。

有一个插件可以解决您的问题:mark.js

用法可以完成,例如以下方式:

$(function(){
  // pass an array to highlight or a simple string term
  $("h1").mark(["Balloon", "Oranges"]);
});
mark{
  background: orange;
  color: black;
}
<script src="https://cdn.jsdelivr.net/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script>
<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>