如果元素包含这些单词中的任何一个,则将该单词包装在 span 中
If element contains any of these words then wrap that word in span
如果某些
单词在标题中找到,我想通过将这些单词包装在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>
你可以有一个包含你想要包装的所有单词的对象(包括另一个规范,例如类或使用的标签),然后只是迭代对象的所有字段,同时使用你的命令来构造要使用的字符串。
相关文章:
- 如何将函数包装在函数中以避免代码重复
- 当鼠标悬停在文本中的单词上时显示警报
- 我怎样才能把p中的一个单词包装在a标签中呢
- 如何在包含 Unicode 字符 'u00A0' 的表中包装单词
- 使用 Javascript 的 replace() 方法用 html 包装单词
- 将单词包装在标签中,保留标记
- 如何在下页编辑器的预览中包装单词
- JavaScript:如何用包含唯一id的span标记将字符串中的每个单词包装起来
- 使用jQuery自动包装DIV中的前一个单词
- 拆分文本并在jQuery元素中包装每个单词
- 如何将元素的每个单词包装在 span 标记中
- Javascript /从字符串中抓取第一个和最后一个单词,然后用class包装
- 在html元素中包装每个单词
- 如何包装html标签为jquery鼠标选择单词
- 将每个单词的第一个字母包装在span标签- javascript中
- Regexp用于包装HTML页面上的每个单词
- 如何在轴标签中只包装一个单词
- Jquery - 在字符串中查找一个单词并用 标签包装它
- 如果元素包含这些单词中的任何一个,则将该单词包装在 span 中
- 在javascript中,在单词边界的span标签中包装每个单词的正则表达式