如果元素包含任何这些单词,则将该单词包含在span

时间:2016-07-09 10:24:47

标签: javascript jquery contains keyword

如果通过在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个左右)用于Balloon或Oranges,然后用span颜色包裹这些单词。

我可以使用:

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

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

4 个答案:

答案 0 :(得分:5)

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

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>

答案 1 :(得分:0)

循环遍历您的元素集,并将其替换为关键字数组中的任何内容:

<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>

答案 2 :(得分:0)

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

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

可以使用例如以下方式:

&#13;
&#13;
$(function(){
  // pass an array to highlight or a simple string term
  $("h1").mark(["Balloon", "Oranges"]);
});
&#13;
mark{
  background: orange;
  color: black;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

您可以拥有一个包含所有要包装的单词的对象(包括其他规范,例如类或使用的标记),然后在使用刚刚构造要使用的字符串的命令时迭代对象的所有字段。 / p>

相关问题