我會用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;
})
如果你真的想基於數據選擇元素,使用custom data attributes和屬性選擇像$("#td[data-something='RedRedRedBlue']")
。