如何在D3 .enter()函数中有条件地追加元素

时间:2016-06-20 21:44:58

标签: d3.js

所有

我想知道如何在D3 .data().enter()中附加不同的元素,例如:

如果我想追加表列,而是将每列作为td附加,我希望第一列为th,所以代码如下:

tbody.append("tr").selectAll("anyplcaeholder").data([1,2,3,4])
     .enter()
// I do not know how to do this folloing

有什么想法吗?感谢

1 个答案:

答案 0 :(得分:2)

你可以用这个:

var table = d3.select('body').append('table');

var tr = table.selectAll('tr')
    .data([1,2,3,4,5]).enter()
    .append('tr');

tr.append('th').html(function(d) { return d; });  // add your condition here
tr.append('td').html(function(d) { return " "; });  // if you need more
tr.append('td').html(function(d) { return " "; });  // columns with data

此代码为您提供以下内容:

<table>
    <tr>
        <th>1</th>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <th>2</th>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr> .....

right way将列标题添加到表格

Here工作的jsFiddle