How to get data of parent node in d3.js

后端 未结 3 1588
北恋
北恋 2020-12-14 14:52

I am doing nesting in D3 and in a nested element, I need to reach data object on its parent.

Right now I am doing

d3.select(this).node().parentNode._         


        
3条回答
  •  旧时难觅i
    2020-12-14 15:19

    I found this post when I had exactly the same issue. My solution, was to change the selection to pass on the data that I will need in the child, which I think might be a valid approach if you can live with the data redundancy in the node.

    [
      {
        title: "Google",
        link: "www.google.com",
        languagePath : "en,fr,it"
      },
    
      ...
    ]
    

    To help explain, I've used this in the context of a table, with two columns. The first column has the title and the second column has an a for each of the accept-language items.

    So I did a sub selections of the split of languagePath and for each enter call, I would create a a with the text being the language.

    So at this point I also need the link, so that the a elements look like:

    EN
    FR
    

    But the link is not part of the data passed to this child, so when I did the selection instead of doing:

    var langLinks = tableRow
         .append("td")
         .selectAll("span")
         .data(function(d) {
            return d.languagePath.split(",")
          })
    

    I did

     var langLinks = tableRow
         .append("td")
         .selectAll("span")
         .data(function(d) {
            return d.languagePath.split(",").map(function(item) {
                     return {
                       lang : item,
                       link : d.link
                   })
          })
    

    And so, when I'm processing data on the enter() of this selection I do have the parent's data.

    Hope this is a valid alternative for some of you, it did help me.

提交回复
热议问题