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

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

本文关键字:单词 包装 span 包含这 元素 单词中 任何一 如果      更新时间:2023-09-26
如果某些

单词在标题中找到,我想通过将这些单词包装在span类中来突出显示这些单词。有没有办法编写要检查的单词列表,然后使用相同的命令将任何单词与span类包装在一起?

例如:

<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 个左右)的单词气球或橙子,然后将这些单词包装在跨度颜色中。

我可以使用:

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

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

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

var words = [
    "balloon",
    "either"
];
$('h1').html(function(_,html) {
    var reg = new RegExp('('+words.join('|')+')','gi');
    return html.replace(reg, '<span class="red">$1</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 生成。此外,您可能需要一次删除高光,因此您要重新反转轮子。

有一个插件可以解决您的问题:标记.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>

你可以有一个包含你想要包装的所有单词的对象(包括另一个规范,例如类或使用的标签),然后只是迭代对象的所有字段,同时使用你的命令来构造要使用的字符串。