Join existing elements of the DOM to data with d3.js

后端 未结 1 373
我在风中等你
我在风中等你 2020-12-09 06:48

I\'m trying to join existing input text (selected by d3.selectAll()) that have unique id\'s corresponding to keys in the data joined with D3. I would like D3 t

1条回答
  •  时光说笑
    2020-12-09 07:34

    Remember that the key function will be invoked on each element of your data array (i.e. dt), as well as on each element in your selection (i.e. d3.selectAll(".input")). In both cases, the key function needs to return a valid value and those output values will used to make the association.

    To achieve your goal you can do something like the following example. See fiddle for live version: http://jsfiddle.net/2Fkjq/

    If your document contains the following:

    ​ then executing this:

    var data = [
        { key: "a", val: "aaa" },
        { key: "b", val: "bbb" },
        { key: "c", val: "ccc" }
    ];
    
    d3.selectAll("div")
        .data(data, function(d) { return (d && d.key) || d3.select(this).attr("id"); })
        .text(function(d) { return d.val; });
    

    will result in this document:

    ccc
    aaa
    bbb

    You see that the key function consists of two parts. The first part is designed for the data array:

    (d && d.key)
    

    That part will return undefined for the elements in the d3 selection. The second part targets those elements:

    d3.select(this).attr("id")
    

    0 讨论(0)
提交回复
热议问题