我想给包含黑名单单词之一的HTML元素添加一个类。

例如,我的黑名单由“坏”和“丑”组成,我想在其范围内添加类:

<div id="main">
    <span>This is good.</span>
    <span class="black">Bad things happen sometimes.</span>
    <span class="black">This is bad.</span>
    <span class="black">And this is ugly.</span>
</div>

<a onclick="blacklisterFunction();">Add Class</a>


blacklisterFunction()的外观如何?该函数应该为每个列入黑名单的单词抓取主要div还是有更有效的方法。

最佳答案

这是一种方法:

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

参考文献:


getElementsByTagName()
match()
RegExp()
test()
textContent

10-08 15:56