检查数组中的条件后的颜色编码表

时间:2013-09-27 01:58:28

标签: jquery json

我正在尝试从数组中检查某些条件后对td进行颜色编码。一切都很好,除了这件作品。这就是我所拥有的

<table border="0" cellpadding="0" cellspacing="0">
    <th>First Name</th>
    <th>Last Name</th>
    <th>Profession</th>
    <th>Code</th>
</table>

var html = "";

$.each(arrayTest, function () {
    html += '<tr><td>' + this.firstName + '</td>';
    html += '<td>' + this.lastName + '</td>';
    html += '<td>' + this.profession + '</td>';
    html += '<td class="colorType"></td><tr>';

    if (this.type === 'red') {
        $('.colorType').css('background', 'red')
    }
    else if (this.type === 'blue') {
        $('.colorType').css('background', 'blue')
    } else {
        $('.colorType').css('background', 'white')
    }
});

$('table').append(html);

这是我的小提琴 http://jsfiddle.net/sghoush1/J2ssK/9/

4 个答案:

答案 0 :(得分:3)

这个怎么样?

$.each(arrayTest, function () {
    html += '<tr><td>' + this.firstName + '</td>';
    html += '<td>' + this.lastName + '</td>';
    html += '<td>' + this.profession + '</td>';    
    html += '<td style="background-color:' + this.type + '"></td><tr>';
});

Updated fiddle

您的问题是您在附加到dom之前引用了dom元素.colorType

答案 1 :(得分:1)

这是因为在将html附加到表之前,颜色周围的if()语句正在运行,因此当您尝试更改颜色时,这些元素不存在。

相反,您可以在循环内部添加样式内联,如下所示:

$.each(arrayTest, function () {
    html += '<tr><td>' + this.firstName + '</td>';
    html += '<td>' + this.lastName + '</td>';
    html += '<td>' + this.profession + '</td>';
    html += '<td class="colorType" style="background:';

    if (this.type === 'red') {
       html += 'red';
    }
    else if (this.type === 'blue') {
       html += 'blue';
    } else {
       html += 'white';
    }
    html += ';"></td><tr>';
});

Here is the updated jsFiddle

答案 2 :(得分:1)

调用$(".colortype").css(...)设置DOM中已有的所有匹配元素的背景。它对您正在构建的HTML字符串没有任何作用。您需要在HTML中添加一些内容,以便为TD提供合适的样式。在这里,我使用了不同的类来表示不同的颜色背景。

添加此CSS:

.redBG {
    background-color: red;
}
.blueBG {
    background-color: blue;
}
.whiteBG {
    background-color: white;
}

并将JS更改为:

$.each(arrayTest, function () {
    html += '<tr><td>' + this.firstName + '</td>';
    html += '<td>' + this.lastName + '</td>';
    html += '<td>' + this.profession + '</td>';
    html += '<td class="' + this.type +'BG"></td><tr>';
});

FIDDLE

答案 3 :(得分:-1)

代码不起作用,因为你只能在追加方法之后用jquery操作'td'

所以试试这个:

$.each(arrayTest, function (i) {
    html = ""; //clean up the variable
    html += '<tr><td>' + this.firstName + '</td>';
    html += '<td>' + this.lastName + '</td>';
    html += '<td>' + this.profession + '</td>';
    html += '<td class="colorType_'+i+'"></td><tr>'; //put the i count, because the class cannot be duplicated

    $('table').append(html);

    if (this.type === 'red') {
        $('.colorType'+i ).css('background', 'red')
    }
    else if (this.type === 'blue') {
        $('.colorType'+i ).css('background', 'blue')
    } else {
        $('.colorType'+i ).css('background', 'white')
    }
});