admin管理员组

文章数量:1334681

I am working on a D3 Scatter Plot having data from different regions - here regions are Continent names like Europe, Asia etc. I want to associate the region with a class name so that I can perform mon activities for one region.

Below is my code to add multiple classes together to an element:

var dot = svg.append("g")
                .attr("class", "dots")
                .selectAll(".dot")
                .data(interpolateData(1900))
                .enter().append("circle")
                .attr("class", "dot " + function(d) { return d.Region; });

When I write the following code to check what classes are associated with the current object.

alert(this.getAttribute('class'));

I got this output:

So I can see that it is adding "dot" class successfully but not able to add Region dynamically.

TIA

I am working on a D3 Scatter Plot having data from different regions - here regions are Continent names like Europe, Asia etc. I want to associate the region with a class name so that I can perform mon activities for one region.

Below is my code to add multiple classes together to an element:

var dot = svg.append("g")
                .attr("class", "dots")
                .selectAll(".dot")
                .data(interpolateData(1900))
                .enter().append("circle")
                .attr("class", "dot " + function(d) { return d.Region; });

When I write the following code to check what classes are associated with the current object.

alert(this.getAttribute('class'));

I got this output:

So I can see that it is adding "dot" class successfully but not able to add Region dynamically.

TIA

Share Improve this question asked Nov 9, 2016 at 10:04 disp_namedisp_name 1,4882 gold badges24 silver badges49 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You have move your function, passing it as the second argument of attr:

.attr("class", function(d){
    return "dot " +  d.Region; 
});

Once I encountered the same problem. I expected d3.js attr() to accept collection of values to represent multiple classes and ended up searching for the solution on this issue.

Multiple classes can be passed as a result of method call:

.attr('class', (d) => `label item${d.itemNr}`);

where label is the first class and item0 is the second one after this code is executed. You can add many more.

This is the result you get:

<text class="label item0" x="543" y="51">Item 0</text>

Maybe the design originates from data driven approach - you have selection of data and want to pass function of data or its result for an attribute's value. At the end, that made sense for me.

本文标签: javascriptAdding multiple class name to an element D3Stack Overflow