我有下表:http://jsfiddle.net/UfhVc/1/
我想:
但是现在我似乎无法弄清楚步骤1)所需的逻辑。可以使用jQuery,我发现使用普通的js更容易。
另外,我在这部分代码中收到警告:
table.rows[i+1].cells[0].innerHTML
答案 0 :(得分:2)
喜欢这个?
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 强>
答案 1 :(得分:0)
第一步:
有几种方法可以做到,我可能会将一个类附加到特定类型的所有表格单元格,因此您可以轻松地一次性选择它们进行编辑。
<table>
<tr>
<td class="id-cell"></td>
</tr>
</table>
然后你可以简单地用CSS查询它:
.id-cell {
background-color:red;
}
但是你也可以使用更多的jQuery / JavaScript来找到你正在寻找的那些表格单元格。这个小提琴使用jQuery来查找&#34; id&#34;中的所有单元格。列,并将背景绘制为红色。
答案 2 :(得分:0)
另一种方法:
$("table tr:not(:first-child) td:first-child").each(function(index) {
var thisId = $(this);
$("table tr:not(:first-child) td:first-child").each(function(_index) {
if (index != _index && thisId.text() == $(this).text())
{
thisId.parent("tr").css("backgroundColor", "red");
$(this).css("backgroundColor", "red");
$(this).siblings("td").each(function(sindex) {
var other = $(thisId.siblings()[sindex]);
if (other.text() != $(this).text())
other.css("backgroundColor", "yellow");
});
}
});
});