在没有jquery的情况下检测多个类名

时间:2013-04-01 01:50:14

标签: javascript jquery

学习DOM0 javascript和教授已经抛出一个曲线球。他用类名写了几十段:体育,生活,书籍,喜剧,然后是:

<p class="sports books comedy">
    I found this book: http://www.amazon.com/Teed-Off-Laughs-Greens-Sports/dp/0233995005/ref=sr_1_1?ie=UTF8&s=books&qid=1277749796&sr=1-1 You don't have to be good to play, but a low level of self-esteem is helpful! Humorous collection of colour photographs and hilarious text reduces our heroes of the golf course to mere mortals. No golfing disaster is left secret and the 80 photographs only go to prove the fallibility of international stars.
</p>

不必使用Jquery来设置样式,我的想法就是这样:

window.onload=function(){
    var elements = document.getElementsByTagName('*');
    for (var i=0; i<elements.length; i++) {
        if (elements[i].className == 'sports') {
            elements[i].style.border="2px solid green";
        }

        else if (elements[i].className == 'life') {
            elements[i].style.color="red";
        }

        else if (elements[i].className=="books") {
            elements[i].style.textAlign="right";
        }

        else if (elements[i].className=="comedy") {
            elements[i].style.fontSize="200%";
        }
    }
}

除了多个类名之外,它适用于所有内容。试图找到解决方法。

2 个答案:

答案 0 :(得分:4)

elements[i].className.indexOf('sports') >= 0
如果任何类都是体育类,

会起作用,但它也会增加子串的问题(也会匹配“其他类型”)

很可能

var classlist;
classlist = elements[i].className.split(/\s+/);
if(classlist.indexOf('sports') >= 0)

这有点冗长,但应该适合你想做的事。

答案 1 :(得分:2)

elements[i].classList.contains('sports')

ben336的答案也适用,并且曾经是最好的方法,但现在有一种本地的方式来做它我们应该更喜欢(因为它更快,代码更少)。唯一的缺点是,如果没有polyfill,它将无法在IE8或IE9中运行。