选择/检测d3.js中已更改的元素? [英] Select/detect the changed elements in d3.js?

查看:93
本文介绍了选择/检测d3.js中已更改的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例如下所示:

a=[1,2,3,4,5];
svg.selectAll("rect").data(a)
a[1]=10;
a[4]=50;
svg.selectAll("rect").data(a)

a 的第五个元素已更改。我只想选择这两个元素,并将它们的颜色设置为红色。但是,我不知道如何做,或者换句话说,在d3.js中选择这些改变的元素。 (据我所知, enter()不能做这项工作)。有没有人有这个想法?

The second and the fifth elements of a are changed. And I want to ONLY select these two elements and set their color as red. However, I don't know how to do that, or in other words, select these changed element in d3.js. (As I understand, enter() can't do this job). Does anyone have ideas about this?

推荐答案

您需要一种方法来存储旧的数据值,以便与新的数据进行比较。也许添加如下的自定义数据属性:

You need a way to store the old data value so that you can compare it against the new one. Maybe add a custom data attribute like this:

a=[1,2,3,4,5];
svg.selectAll("rect").data(a)
    .attr("data-currentVal", function(d){return d});
a[1]=10;
a[4]=50;
svg.selectAll("rect").data(a)
    .style("fill", function(d) {
       if (d3.select(this).attr("data-currentVal") != d) {return red;}
       else {return black;}
    });

活动示例(略微浮现,以便您可以看到更改发生):

http://fiddle.jshell.net/5Jm5w/1/

Live example (slightly fancied up so you can see the changes happening):
http://fiddle.jshell.net/5Jm5w/1/

当然,对于更常见的例子,其中d是一个复杂的对象,你需要有一个方法来访问它的值作为一个唯一的字符串,因为属性值将永远强制转换为字符串。例如,如果你有一个(x,y)点,你需要创建一个命名的帮助函数,如 dToString = function(d){return(+ dx +,+ dy + );} ,然后在设置属性时传递该函数的名称,并在比较旧的和新的时使用它。

Of course, for the more common example where d is a complex object, you would need to have a way of accessing it's value(s) as a unique string, since the attribute value would always be coerced to string. For example, if you have an (x,y) point, you would need to create a named helper function like dToString = function(d) {return "(" + d.x + "," + d.y + ")";}, and then pass in the name of that function when you set the attribute, and use it again when you compare the old and new.

这篇关于选择/检测d3.js中已更改的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆