如何更改javascript,以便所有关键字都可以在内容中自动突出显示。 目前,当用户点击关键字时,关键词将突出显示。 我想自动突出显示它。 但我不知道如何更改javascript。
<h3>Keywords</h3>
<ul id="keywords">
<li><span>AC</span> <span>Motors<span></li>
<li><span>Adjustable</span> <span>Speed</span> <span>Motor</span> <span>Drives<span></li>
</ul>
<h3>Sentences</h3>
<table style="font-size: 0.9em;">
<tr>
<td class="context">columbus fan & machine corp, dc industrial sales company, ac motors, dc motors, electric motor repair, electrical product servicing, cooling blowers, cooling blower filters, line/load reactors, electrical products, electric product distributors, power products, dc drives, electrical enclosures, electrical generators, electrical heaters, electric pumps, proximity switches, electrical transformers, electrical tachometers</td>
</tr>
<tr>
<td class="context">Columbus Fan & Machine corp is a <span class="featured-word">manunfacturer</span> of top quality Cooling Blowers and Filters along with other related motor accessories for all makes of AC & DC Motors</td>
</tr>
</table>
的javascript:
$(document).ready(function () {
var context = document.querySelectorAll('.context')
, keywords = document.querySelector('#keywords');
keywords.addEventListener('click', function (event) {
var target = event.target;
for(var i = 0; i < context.length; i++) {
var item = context[i]
, text = item.textContent
, featuredWords = item.querySelectorAll('.featured-word')
, words = Array.prototype.slice.call(featuredWords, 0).map(function(node) {
return node.textContent;
})
, regex = new RegExp('\\b(' + target.textContent + ')\\b', 'ig');
text = text.replace(regex, '<span class="highlight">$1</span>');
// put the bolded words back
words.forEach(function(word) {
text = text.replace(word, '<span class="featured-word">'+word+'</span>');
});
item.innerHTML = text;
}
}, false);
});
的CSS:
.highlight {
background-color: yellow;
}
.featured-word {
color: red;
font-weight: bold;
}
答案 0 :(得分:0)
而不是点击&#39;点击&#39;关键字的事件..只需在窗口加载自己的所有关键字,如下所示,
$(document).ready(function() {
var context = document.querySelectorAll('.context'),
keywords = document.querySelectorAll('ul#keywords li span');
Array.from(keywords).forEach(function(entry) {
for (var i = 0; i < context.length; i++) {
var item = context[i],
text = item.innerHTML,
featuredWords = item.querySelectorAll('.featured-word'),
words = Array.prototype.slice.call(featuredWords, 0).map(function(node) {
return node.textContent;
})
, regex = new RegExp('\\b(' + entry.innerHTML + ')\\b', 'ig');
text = text.replace(regex, '<span class="highlight">$1</span>');
// put the bolded words back
words.forEach(function(word) {
text = text.replace(word, '<span class="featured-word">' + word + '</span>');
});
item.innerHTML = text;
}
}, false);
});