如果可能的话,我会使用 d3 来构建表格:http: //jsfiddle.net/ztGE9/2/
var data = [["Red","Blue","Blue"], ["Red"], ["Blue"], ["Red", "Blue"], ["Red", "Blue", "Red"], ["Red","Red","Red","Red","Blue"]];
var table = d3.select("#container").append("table"),
tbody = table.append("tbody");
var rows = tbody.selectAll("tr")
.data(data)
.enter().append("tr");
var cells = rows.selectAll("td")
.data(function (row) {
var tally = {Red:0,Blue:0};
row.forEach(function(item) {
tally[item]++;
});
return ["rgba(255,0,0,"+ tally["Red"]*0.1 +")",
"rgba(0,0,255,"+ tally["Blue"]*0.1 +")"];
})
.enter()
.append("td")
.text("foo")
.style("background-color", function(d) {
console.log(d);
return d;
});
如果您的 HTML 已经在其中编码了表格,那么您可以获取每个文本的文本td
并使用正则表达式来计算事物——无需根据数据本身来选择事物。见这里:http: //jsfiddle.net/aKtct/。
var tds = document.getElementsByTagName("td"),
forEach = Array.prototype.forEach;
forEach.call(tds, function (td) {
var redMatch = td.textContent.match(/Red/g),
redCt = redMatch && redMatch.length || 0,
blueMatch = td.textContent.match(/Blue/g),
blueCt = blueMatch && blueMatch.length || 0;
var rgba = redCt ? "rgba(255,0,0," + 0.1 * redCt + ");" :
"rgba(0,0,255," + 0.1 * blueCt + ");";
td.style.cssText += "background-color:" + rgba;
})
如果您真的想根据数据选择元素,请使用自定义数据属性和属性选择器,例如$("#td[data-something='RedRedRedBlue']")
.