这是一种方法:
function blacklister(el, words) {
if (!el || !words) {
return false;
}
else {
var text = el.textContent;
for (var i = 0, len = words.length; i < len; i++) {
if (text.test(new RegExp(words[i],'gi'))) {
el.className += 'black';
}
}
}
}
var m = document.getElementById('main'),
spans = m.getElementsByTagName('span'),
blacklist = ['ugly','bad'];
for (var i = 0, len = spans.length; i < len; i++) {
blacklister(spans[i],blacklist);
}
JS 小提琴演示。
为响应 OP 留下的评论而编辑,在 Firefox 中使用上述内容报告错误:
>
function blacklister(el, words) {
if (!el || !words) {
return false;
}
else {
var text = el.textContent;
for (var i = 0, len = words.length; i < len; i++) {
if (text.match(new RegExp(words[i],'gi'))) {
if (el.className.indexOf('black') == -1){
el.className += 'black';
}
}
}
}
}
var m = document.getElementById('main'),
spans = m.getElementsByTagName('span'),
blacklist = ['ugly','bad'];
for (var i = 0, len = spans.length; i < len; i++) {
blacklister(spans[i],blacklist);
}
JS 小提琴演示。
参考: