如何用D3.js基于JSON数据为表格单元格设置id与class
Fixing D3.js Table Cell IDs and Classes for Specific Columns
Got it, let's fix this up for you! The main problem with your current code is that when you're preparing data for each table cell, you're only passing along the column name and cell value—so D3 doesn't have access to the original row's code and norm values when you want to set the id and class attributes.
Here's the adjusted code that will generate the table exactly as you want:
var data = [{ "code": 100, "name": "A", "unit": 12, "value": 0.6, "target": 0.75, "norm": "alert" }, { "code": 106, "name": "B", "unit": 12, "value": 0.6, "target": 0.75, "norm": "danger" }, { "code": 112, "name": "C", "unit": 12, "value": 0.9, "target": 0.75, "norm": "ok" }]; var columns = ['name', 'target', 'value']; var table1 = d3.select('#table').append('table'); var thead = table1.append('thead'); var tbody = table1.append('tbody'); // Append the header row thead.append('tr') .selectAll('th') .data(["Name", "Target", "Value"]) .enter() .append('th') .text(function(column) { return column; }); // Create a row for each object in the data var rows = tbody.selectAll('tr') .data(data) .enter() .append('tr'); // Create a cell in each row for each column var cells = rows.selectAll('td') .data(function(row) { return columns.map(function(column) { // Include the original row's code and norm in the data object return { column: column, value: row[column], code: row.code, norm: row.norm }; }); }) .enter() .append('td') .html(function(d) { return d.value; }) // Set id only for the 'name' column cells, using the row's code .attr('id', function(d) { return d.column === 'name' ? d.code : null; }) // Set class only for the 'name' column cells, using the row's norm .attr('class', function(d) { return d.column === 'name' ? d.norm : null; });
Key Changes Explained:
- Pass extra data to cells: When mapping columns to cell data, we now include the original row's
codeandnormvalues. This gives D3 access to those properties when we need to set attributes. - Conditionally set id and class: Using D3's
.attr()method with a function, we check if the current cell is for thenamecolumn. If it is, we set the id tocodeand class tonorm; otherwise, we leave those attributes unset (by returningnull).
This will produce exactly the HTML structure you're expecting, with only the first column's cells having the id and class applied.
内容的提问来源于stack exchange,提问作者Rob Wissink
相关产品推荐
相关产品推荐

