這裏有一個辦法:
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 Fiddle demo。
編輯響應評論通過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 Fiddle demo。
參考文獻:
你需要一個span類到這些單詞或句子嗎? – Katti
整個句子將被定義爲一個不好的單詞。 – sevenkul