Appending multiple non-nested elements for each data member with D3.js

后端 未结 6 1878
无人及你
无人及你 2020-12-04 19:14

I would like to create multiple non-nested elements using d3 to create a structure like this:

    

from data[0] &l

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 19:48

    The idomatic way of doing is with nesting:

    var divs = d3.select('#parent').selectAll('p').data(data).enter().append('div');
    
    divs.append('p')
    divs.append('p')
    

    Which creates:

    from data[0]

    from data[0]

    from data[1]

    from data[1]

    from data[2]

    from data[2]

    If that won't work, save your selection and repeatedly append:

    var enterSelection = d3.select('#parent').selectAll('p').data(data).enter();
    
    enterSelection.append('p')
    enterSelection.append('p')
    

    then sort what you've added:

    d3.select('#parent').selectAll('p').sort(function(a, b){ return a.index - b.index; })
    

    You'll need to add an index property to each element of data that describes the sort order. The normal i is only defined in the context of a particular selection, which is lost when we reselect.

提交回复
热议问题