我有下表:http://jsfiddle.net/UfhVc/1/
我正在尝试:
- 在具有相同 ID 的所有行上获取相同的样式
- 突出显示具有相同 ID 的各行中的差异。
但现在我似乎无法弄清楚步骤 1) 所需的逻辑。使用 jQuery 没问题,我只是发现使用纯 js 更容易。
此外,我在这部分代码中收到警告:
table.rows[i+1].cells[0].innerHTML
最佳答案
像这样吗?
var newColor = "#F1D0F2";
var diffColor = "#CECECE";
$('#tbl tr:gt(0)').each(function () { //Loop through the trs leaving out the header
var txt = $(this).find('td:eq(0)').text(); //get the text of the id column
var $this = $(this);
var matchingRows = $('#tbl tr').not(this).filter(function () { //get the matching rows whose id colum value is same
return $(this).find('td:eq(0)').text() == txt;
}).css('background-color', newColor); //apply css for match
matchingRows.find('td').css('background-color', function (i) { //apply background color
if ($this.find('td:eq(' + i + ')').text() != this.innerHTML) return diffColor; // to the tds of matching rows but column valud differ.
});
});
<强> Fiddle
引用文献:
编辑
根据您的评论,更新如下:
var allColors = ["#333333","#990099", "#1295A6", "#FFFF99"]; //Set up the colors in to an array
var diffColor = "#CECECE";
$('#tbl tr:gt(0)').each(function () {
var txt = $(this).find('td:eq(0)').text();
var $this = $(this);
if($this.is('.transformed')) //check for class transformed is present if so this has already been processed skip it.
return;
//Get the matching rows whose id column value is same
var matchingRows = $('#tbl tr').filter(function () {
return $(this).find('td:eq(0)').text() == txt;
}).css('background-color', allColors.shift()).addClass('transformed'); //Set the color and add a class to avoid latter processing
matchingRows.find('td').css('background-color', function (i) { //apply background color
var $parTd = $this.find('td:eq(' + $(this).index() + ')');
if ($.trim($parTd.text()) != $.trim(this.innerHTML)) // to the tds of matching rows but column value differ.
{
$parTd.css('background-color', diffColor);
return diffColor;
}
});
});
<强> Fiddle
关于javascript - 根据内容设置表格样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17324405/