编写此jquery函数的更简洁或更简单的方法? 这是基于同一行中另一列的值对mvc网格列进行样式更改的正确方法吗 是否有更好/更干净或更简单的方法来实现类似的功能

编写此jquery函数的更简洁或更简单的方法? 这是基于同一行中另一列的值对mvc网格列进行样式更改的正确方法吗 是否有更好/更干净或更简单的方法来实现类似的功能,jquery,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)

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

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');

    });
}
如果文本始终是这3个属性之一,则可以删除
If
复选框,或者更好地使用数组而不是对象:

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);
        }
    });
}

这是codereview.stackexchange的问题。com@RussJ我是否应该在此处删除此内容并在此处重新发布?是的,因为您正在寻找建议/建议,这样更合适。
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);
    });
}