2012-09-27 86 views
1

我需要根據數據的內容選擇特定的元素。基於數據的元素選擇

假設我有兩個單元格的表格,紅色&藍色。我有一堆表格的數據["Red", "Blue", "Blue", ... ]

我的問題是如何根據匹配數據的數量修改適當的單元格。例如,如果有5個藍色和3個紅色,藍色單元的背景爲#00f,不透明度爲50%,紅色爲#f00,不透明度爲30%。

到目前爲止,我只看到通過過濾修改集合中所有元素(例如,selectAll("p"))或甚至子部分的功能。

有沒有辦法根據數據選擇特定的元素?

回答

0

我會用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']")