d3 adding data attribute conditionally

后端 未结 5 1381
悲&欢浪女
悲&欢浪女 2021-02-01 14:01

I\'m creating a table with d3 to be used by the FooTable jquery plugin and this requires having some data- attributes in the header row. But not all columns have all the data a

5条回答
  •  隐瞒了意图╮
    2021-02-01 14:46

    Seems like a good candidate for .each():

    var th = d3.select(selection).select("thead").selectAll("th")
            .data(colspec)
        .enter().append("th")
            .text(function(d) { return d["data-name"]; })
            // now address each item individually
            .each(function(d) {
                var header = d3.select(this);
                // loop through the keys - this assumes no extra data
                d3.keys(d).forEach(function(key) {
                    if (key != "data-name")
                        header.attr(key, d[key]);
                });
            });
    

    I often use .each when having a per-item scope makes more sense than trying to figure out a bunch of attributes for each item.

    For a short list of attributes, especially if you're worried about extra data in the objects, it's probably easier to loop through the desired keys instead of everything:

            .each(function(d) {
                var header = d3.select(this);
                ['data-class', 'data-hide', 'data-ignore'].forEach(function(key) {
                    if (key in d)
                        header.attr(key, d[key]);
                });
            });
    

提交回复
热议问题