最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Selectdetect the changed elements in d3.js? - Stack Overflow

programmeradmin2浏览0评论

The example looks like this:

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

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?

The example looks like this:

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

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?

Share Improve this question edited Dec 24, 2013 at 16:20 mdml 22.9k8 gold badges60 silver badges66 bronze badges asked Dec 24, 2013 at 15:11 Hanfei SunHanfei Sun 47.2k41 gold badges135 silver badges252 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

There might be a better way of doing this:

//update data array
a[4]=50;

//color update elements
svg.selectAll('rect')
    .filter(function(d, i){ return d != a[i]; })
    .style('color', 'red')

//bind updated data
svg.selectAll('rect').data(a)

You need a way to store the old data value so that you can pare 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;}
    });

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

Of course, for the more mon example where d is a plex 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 pare the old and new.

发布评论

评论列表(0)

  1. 暂无评论