2

我有各种 div 的类名:

 box blue full

 box blue border purple

 box purple full

 box white purple border

 box purple border

 box purple full

 box blue border

 box white

 box white purple border

每行都是一个单独的 div,带有它的特定类名。除了蓝色、紫色和白色之外,还可能有红色和绿色。

我想要做的是:我正在遍历每个 div,并且我想检查以确保 div 的类名不超过 1 种颜色(白色和另一种颜色除外)

所以比如“box blueborder Purple”是不行的,我需要把它改成“box white”的类名

所以基本上,任何具有两种颜色的 div 都需要更改为框白色

如果你想看一个例子,我正在处理这个: http: //k.p2digital.net/如果你点击红色框,然后点击左上角第三列的框,您刚刚创建的红色框左侧的框变为红色......但由于它位于另一个纯色框之间,这不是它自己的颜色,它应该变成白色。

我有一个循环,在您单击运行后,我将在此处检查以确保没有具有两种不同颜色的框(意味着该框位于两个纯色框之间)并且需要更改为白色

 for(var i = 0; i < 36; i++){
        console.log($(".box[rel='"+[i]+"']").attr('class'));    
        class = $(".box[rel='"+[i]+"']").attr('class');



    }
4

3 回答 3

3

用这个

colArr=new Array('red','blue',...);
$('div.box').each(function(){
    var i,index;
    i=0;
    for(index in colArr){
        if($(this).hasClass(colArr[index])){
            i+=1;
        }
    }
    if(i>1){
        for(index in colArr){
            if($(this).hasClass(colArr[index])){
                $(this).removeClass(colArr[index]);
            }
        }
        $(this).addClass('white');
    }
});
于 2013-04-14T20:23:23.823 回答
3

如果您想要一个有效的解决方案,您可以计算每个项目中的颜色,如果太多,请将类名设置为非颜色类名加白色:

// create map of all color names for fast lookup
var colors = {
    red: true,
    blue: true,
    purple: true,
    white: true
    // ...
};

$(".box").each(function() {
    // get each class name separately into an array
    var classes = this.className.split(" ");
    var colorCnt = 0, nonColors = [];
    for (var i = 0; i < classes.length; i++) {
        if (colors[classes[i]]) {
            // count the matching color
            ++colorCnt;
        } else {
            // save the non-color class name
            nonColors.push(classes[i]);
        }
    }
    // if too many colors, then set class name to all non-colors plus white
    if (colorCnt >= 2) {
        nonColors.push("white");
        this.className = nonColors.join(" ");
    }
});
于 2013-04-14T20:31:53.737 回答
2

那这个呢:

$('.box').attr('class', function() {
    var m = this.className.match(/blue|purple|white|red/g);
    if (m.length > 1) {
        return this.className.replace(RegExp(m.join('|'), 'g'), '') + ' white';
    }
});

例如对于带有类的框box blue border purple

"box blue border purple".match(/blue|purple|white|red/g) // ["blue", "purple"]

http://jsfiddle.net/9U3JH/2/

于 2013-04-14T20:26:19.903 回答