我正在尝试使用 d3 为我的图表制作图例,我想我可以使用一个表格,每行包含以下 HTML:
<tr>
<td class="swatch" style="background: red;"></td>
<td>user</td>
<td>123</td>
</tr>
最终结果类似于 this .
我将数据按照以下形式整齐地放置在每一行上:
{color: 'red', key: 'user', value: 123}
我使用此代码来创建单元格:
let cells = d3.selectAll('tr').selectAll('td')
.data(function (d) {
return [d.color, d.key, d.value];
});
cells.enter().append('td').merge(cells)
.text(function (d, i) {
return i == 0 ? '' : d;
})
.style('background', function(d, i) {
return i == 0 ? d : '';
})
.each(function(d, i) {
if (i == 0) {
this.classList.add('swatch');
}
});
该代码工作正常,但由于重复的 i == 0
检查以特例第一个单元格的行为,它看起来真的很难看。我可以使用更干净的方法吗?
看起来也许我应该使用 text
设置所有内容,并使用 CSS 将其样式设置为颜色样本,但是 isn't possible .
最佳答案
由于不同的表格单元格的操作方式截然不同,因此您可以使用多个附加和类来分隔元素。它看起来像这样:
let cells = d3.select('tbody').selectAll('tr').data(bindData);
let cellsEnter = cells.enter().append('tr');
let swatches = cellsEnter.append('td').classed('swatch', true);
d3.selectAll('table .swatch')
.style('background', function (d) { return d.color });
let otherCells = d3.selectAll('table tr').selectAll('.other')
.data(function (d) {
return [d.key, d.value];
});
otherCells.enter()
.append('td').classed('other', true)
.merge(otherCells).text(function (d) { return d; });
这是一个工作片段:
function updateData(bindData) {
let cells = d3.select('tbody').selectAll('tr').data(bindData);
let cellsEnter = cells.enter().append('tr');
let newSwatches = cellsEnter.append('td').classed('swatch', true);
d3.selectAll('table .swatch')
.style('background', function (d) { return d.color });
let otherCells = d3.selectAll('table tr').selectAll('.other').data(function (d) {
return [d.key, d.value];
});
otherCells.enter()
.append('td').classed('other', true)
.merge(otherCells).text(function (d) { return d; });
}
var data = [
{ color: 'red', key: 'agnes', value: '1' },
{ color: 'green', key: 'bernard', value: '2' },
{ color: 'blue', key: 'connie', value: '3' }
];
updateData(data);
.swatch {
display: inline-block;
height: 10px;
width: 10px;
}
<script src="https://d3js.org/d3.v4.js"></script>
<div id="legend">
<table>
<tbody>
</tbody>
</table>
</div>
关于javascript - 使用d3根据索引优雅地执行不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50766390/