javascript 如何使用 d3 分类选择将名称作为函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17452453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:24:06  来源:igfitidea点击:

How can I use d3 classed selection to have name as function

javascriptd3.js

提问by Priyanka dudani

I am using d3 classed selectionsand in first parameter, instead of a string, I want to use a function that will returns class name.

我正在使用d3 分类选择,并且在第一个参数中,而不是字符串,我想使用一个将返回类名的函数。

selection.classed(name[, value])

I understand I can do the same using .attr()as mentioned here, but I want to be able to do the same using classed.

我知道我可以使用这里.attr()提到的方法来做同样的事情,但我希望能够使用 classed 来做同样的事情。

How can I do this?

我怎样才能做到这一点?

回答by Lars Kotthoff

The class name you provide there needs to be fixed, i.e. you cannot have something like function(d) { return d; }. If you need the class name to be determined by the data, you need to use .attr("class", ...).

您在那里提供的类名需要固定,即您不能有类似function(d) { return d; }. 如果需要通过数据来确定类名,则需要使用.attr("class", ...).

If you're worried about overwriting existing class names, note that you can retrieve and prepend those as follows.

如果您担心覆盖现有的类名,请注意您可以按如下方式检索和添加这些名称。

.attr("class", function(d) { return d3.select(this).attr("class") + " " + d; })

回答by bm1729

I encountered a similar problem in which I wanted to add one class if a property on my datum was true and a different class if the property was false:

我遇到了一个类似的问题,如果我的数据上的属性为真,我想添加一个类,如果属性为假,我想添加一个不同的类:

selection.classed('class-one', function(d) { return d.property; })
    .classed('class-two', function(d) { return d.property; });

If you have a small number of classes to add then something like this might be worth considering.

如果您要添加少量类,那么可能值得考虑这样的事情。

回答by BM-

Similar to the suggested answer, but I found

类似于建议的答案,但我发现

selection.each(function(d) { d3.select(this).classed(d.class, true)

also works.

也有效。

回答by Neal

Lars answer is great, but if you start out with no class on the attribute it will add the class 'null' to the element as the null attribute is forced to a string. Natural next step from his:

Lars 的回答很好,但是如果您开始时没有属性上的类,它会将类 'null' 添加到元素中,因为 null 属性被强制为字符串。从他的自然下一步:

.attr("class", function(d) {
      var existing = d3.select(this).attr("class") 
      if (existing == null){
        return d.column.class
      }else{
        return existing + " " + d.column.class
      }
})

This could be made into a one-liner with a ternary operator if you want it more concise

如果您希望它更简洁,可以将其制成带有三元运算符的单行