SVG databinding based on key

为君一笑 提交于 2019-12-12 04:14:46

问题


I have an svg like below

<g>
   <path d="M150 0 L75 200 L225 200 Z" id='path1'/>
   <path d="M151 0 L75 200 L225 100 Z" id='path2'/>
   <path d="M152 0 L75 200 L225 300 Z" id='path3'/>
   <path d="M153 0 L75 200 L225 400 Z" id='path4'/>
</g>

And I have a data.json like

{
    [
      "path2",
      "22218",
      "26627",
      "29101"
    ],
    [
      "path4",
      "218",
      "207",
      "160"
    ]
    [
      "path3",
      "22218",
      "26627",
      "29101"
    ],
    [
      "path1",
      "218",
      "207",
      "160"
    ]
}

I am confused as how to bind the data based on the key.I am assuming that I can use the first element in each array as the data-key. But how do I use it in the .data() function?

Any suggestions?


回答1:


First, you'll want to assign 'dummy' data to the existing elements, based on some attribute of that element (in this case, the 'id' attribute) using selection.datum. The data you assign should put the identifier in the same format you'll be using with your actual input data (in this case, index 0 of the array is the identifier):

var paths = d3.selectAll("path")
    .datum(function(d) { return [d3.select(this).attr("id")]; })

Then, you can assign data to these paths, and use a key function, as per usual:

    .data(data, function(d) { return d[0]; });

To test, you can print to the console:

paths.each(function(d) { console.log(this, d); });

which in this case, outputs:

<path id="path2" d="M151 0 L75 200 L225 100 Z"> ["path2", "22218", "26627","29101"]
<path id="path4" d="M153 0 L75 200 L225 400 Z"> ["path4", "218", "207", "160"]
<path id="path3" d="M152 0 L75 200 L225 300 Z"> ["path3", "22218", "26627", "29101"]
<path id="path1" d="M150 0 L75 200 L225 200 Z"> ["path1", "218", "207", "160"]

jsfiddle here.



来源:https://stackoverflow.com/questions/22990350/svg-databinding-based-on-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!