使用 d3.js 将 DOM 的现有元素连接到数据 [英] Join existing elements of the DOM to data with d3.js

查看:17
本文介绍了使用 d3.js 将 DOM 的现有元素连接到数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加入现有的输入文本(由 d3.selectAll() 选择),这些文本具有与 D3 连接的数据中的键对应的唯一 ID.我希望 D3 将输入元素的 id 与数据的键相关联,但事实并非如此.

关联是按照它们分别出现在 DOM 和数组中的顺序完成的.

有没有办法做到这一点?

解决方案

请记住,将在数据数组的每个元素(即 dt)以及选择中的每个元素(即 d3.selectAll(".input")).在这两种情况下,键函数都需要返回一个有效值,这些输出值将用于进行关联.

为了实现您的目标,您可以执行类似于以下示例的操作.现场版本见小提琴:http://jsfiddle.net/2Fkjq/

如果您的文档包含以下内容:

<div id="a"></div><div id="b"></div>

然后执行这个:

var 数据 = [{ key: "a", val: "aaa" },{ 键: "b", val: "bbb" },{ 键: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; });

将导致此文档:

ccc

<div id="a">aaa</div><div id="b">bbb</div>

你看到key函数由两部分组成.第一部分是为数据数组设计的:

(d && d.key)

该部分将为 d3 选择中的元素返回 undefined.第二部分针对这些元素:

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

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 to associate the ids of the input elements to the keys of the data, but it doesn't.

Association is done in the order in witch they appear in the DOM and in the array respectively.

Is there a way to do this ?

解决方案

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:

<div id="c"></div>
<div id="a"></div>
<div id="b"></div>

​ 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:

<div id="c">ccc</div>
<div id="a">aaa</div>
<div id="b">bbb</div>

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")

这篇关于使用 d3.js 将 DOM 的现有元素连接到数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆