Understanding how D3.js binds data to nodes

前端 未结 3 1485
春和景丽
春和景丽 2020-12-22 18:53

I\'m reading through the D3.js documentation, and am finding it hard to understand the selection.data method from the documentation.

This is the example code given

3条回答
  •  猫巷女王i
    2020-12-22 19:50

    When you write:

    ….data(someArray).enter().append('foo');
    

    D3 creates a bunch of elements, one for each entry in the array. More importantly, it also associates the data for each entry in the array with that DOM element, as a __data__ property.

    Try this:

    var data = [ {msg:"Hello",cats:42}, {msg:"World",cats:17} ]; 
    d3.select("body").selectAll("q").data(data).enter().append("q");
    console.log( document.querySelector('q').__data__ );
    

    What you will see (in the console) is the object {msg:"Hello",cats:42}, since that was associated with the first created q element.

    If you later do:

    d3.selectAll('q').data(function(d){
      // stuff
    });
    

    the value of d turns out to be that __data__ property. (At this point it's up to you to ensure that you replace // stuff with code that returns a new array of values.)

    Here's another example showing the data bound to the HTML element and the ability to re-bind subsets of data on lower elements:

      no description

提交回复
热议问题