d3.js v4: How to access parent group's datum index?

前端 未结 8 689
萌比男神i
萌比男神i 2020-11-28 10:33

The description of the selection.data function includes an example with multiple groups (link) where a two-dimensional array is turned into an HTML table.

8条回答
  •  情深已故
    2020-11-28 11:16

    Here's an example of how to use the selection.each() method. I don't think it's messy, but it did slow down the render on a large matrix. Note the following code assumes an existing table selection and a call to update().

    update(matrix) {
            var self = this;
            var tr = table.selectAll("tr").data(matrix);
    
            tr.exit().remove();
    
            tr.enter().append("tr");
    
            tr.each(addCells);
    
            function addCells(data, rowIndex) {
                var td = d3.select(this).selectAll("td")
                    .data(function (d) {
                        return d;
                    });
                td.exit().remove();
    
                td.enter().append("td");
    
                td.attr("class", function (d) {
                    return d === 0 ? "dead" : "alive";
                });
    
                td.on("click", function(d,i){
                    matrix[rowIndex][i] = d === 1 ? 0 : 1; // rowIndex now available for use in callback.                   
                });
            }
    
            setTimeout(function() {
                update(getNewMatrix(matrix))
            }, 1000);
        },
    

提交回复
热议问题