首页 > 解决方案 > 编写此 jquery 函数的更清洁或更简单的方法?

问题描述

function foo() {
    $('#bar > table > tbody > tr').each(function () {
        $(this).find('td:nth-child(3)').text() == '1' && $(this).find('td:nth-child(1)').css('background-color', 'green');
        $(this).find('td:nth-child(3)').text() == '2' && $(this).find('td:nth-child(1)').css('background-color', 'yellow');
        $(this).find('td:nth-child(3)').text() == '3' && $(this).find('td:nth-child(1)').css('background-color', 'red');

    });
}
  1. 这是根据同一行中另一列中的值对 mvc 网格列进行样式更改的正确方法吗?
  2. 是否有更好/更清洁或更简单的方法来实现类似的功能?

标签: jquery

解决方案


使用按文本索引的对象来查找,其值是要设置的颜色:

const colorsByText = {
    1: 'green',
    2: 'yellow',
    3: 'red'
};
function foo() {
    $('#bar > table > tbody > tr').each(function () {
        const text = $(this).find('td:nth-child(3)').text();
        const color = colorsByText[text];
        if (color) {
            $(this).find('td:nth-child(1)').css('background-color', color);
        }
    });
}

如果文本将始终是这 3 个属性之一,则可以删除if检查 - 或者,更好的是,使用数组而不是对象:

const colors = ['green', 'yellow', 'red'];
function foo() {
    $('#bar > table > tbody > tr').each(function () {
        const text = $(this).find('td:nth-child(3)').text();
        const color = colors[text - 1];
        $(this).find('td:nth-child(1)').css('background-color', color);
    });
}

推荐阅读