如何将类添加到包含黑名单单词的元素中

时间:2012-05-30 20:25:36

标签: javascript regex blacklist

我想在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,或者是否有更有效的方式。

2 个答案:

答案 0 :(得分:2)

使用jQuery:

$('#clickme').click(function () {

    $('div span').each(function() {

        var badthings = ['bad', 'ugly', 'gross'];

        var x = 0;

        while (x <= (badthings.length - 1)) { 

            if ($(this).text().toLowerCase().search(badthings[x]) !== -1) {

                $(this).addClass('black');

            }

            x++;

        }

    });

});

jsfiddle:http://jsfiddle.net/DgpnQ/4/

答案 1 :(得分:1)

这是一种方法:

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中使用上述内容报告错误:

&GT;

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

参考文献: