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

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

问题描述

我正在尝试加入现有的输入文本(由 d3.selectAll()选择)具有与D3连接的数据中的键对应的唯一ID。
我想让D3将输入元素的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.

关联是按照它们在DOM和数组中的顺序排列的。

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 ?

推荐答案

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

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.

为了实现你的目标,你可以做如下例。请参阅fiddle for live version: http://jsfiddle.net/2Fkjq/

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; });

将导致此文档:

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

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

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天全站免登陆