Change colour of table cells depending on value

前端 未结 3 1587
走了就别回头了
走了就别回头了 2021-01-26 12:53

I\'m using jQuery to edit the background-color of table cells. My code is as follows (the each cell has numbers in the format \"x/y\" so I mine them out at the star

相关标签:
3条回答
  • 2021-01-26 13:29

    Thanks Nunners, there were header values that broke the code. I've fixed it using the following if block:

    if(vals[1] == undefined){
        return true;
    } else{
        //change colour
    }
    
    0 讨论(0)
  • 2021-01-26 13:31

    Just as Jason P mentioned the following code should work fine :

            $(document).ready(function () {
                $("#overview td").each(function () {
    
                    var content = $(this).html();
                    var vals = content.split("/");
                    var ratio = vals[0] / vals[1];
                    alert(ratio);
    
    
                    var red;
                    var green;
    
                    if (vals[1] == 0) {
                        $(this).css('background-color', '#00FF00');
                    } else {
                        if (ratio > 0.5) {
                            red = 255;
                            green = parseInt(-2 * 255 * ratio + (2 * 255));
                        } else {
                            green = 255;
                            red = parseInt(2 * 255 * ratio);
                        }
                        var rgbColor = 'rgb(' + red + ',' + green + ', 0)';
                        var hexColor = rgb2hex(rgbColor);
                        $(this).css('background-color', hexColor);
                    }
                });
            });
    

    The .each method is just simply an iteration over the retrieved objects.

    0 讨论(0)
  • 2021-01-26 13:33

    Just trigger click event:

    $(document).ready(function() {
        $("#overview td").click(function (event) {
            // ...
        })
        .trigger('click');
    });
    
    0 讨论(0)
提交回复
热议问题