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).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');
});
}
- 这是根据同一行中另一列中的值对 mvc 网格列进行样式更改的正确方法吗?
- 是否有更好/更清洁或更简单的方法来实现类似的功能?
解决方案
使用按文本索引的对象来查找,其值是要设置的颜色:
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);
});
}
推荐阅读
- python - Pyspark TypeError:在数据框列上应用 UDF 时,“NoneType”对象不可调用
- c# - Am I using C# delegates in a useful way?
- batch-file - 批处理文件:暂停后重新启动?
- flutter - 如何在 Flutter 上向 Google 地图添加圆形照片标记?
- ios - UIViewController 在呈现另一个后不会释放
- sql - R、SQL 和现有对象不存在
- web-applications - 我想在 Cypress 中使用 InnerText 值进行进一步计算
- python - 为什么在读取 .json 文件时出现此错误?
- python - 如何将bash输出获取到变量并随后在python中隐藏输出
- html - SVG change circle speed duration for each separate drawing