gpt4 book ai didi

html - 如何使用 d3.js 创建定义列表?

转载 作者:搜寻专家 更新时间:2023-10-31 22:13:16 24 4
gpt4 key购买 nike

我正在尝试创建一个这样的定义列表:

<dl>
<dt>term1</dt>
<dd>definition1</dd>
<dt>term2</dt>
<dd>definition2</dd>
<dt>term3</dt>
<dd>definition3</dd>
</dl>

通过使用这种形式的 JSON:

{
"term1":"definition1"
"term1":"definition2"
"term3":"definition3"
}

.用 d3.js 做这件事最优雅的方法是什么? ?

附注:我想使用 <dl>元素,因为它似乎是语义表示键值对的最合适方式:

最佳答案

d3 v3.x 的解决方案;从 d3 4.0 开始不再有效

我在同一个问题上苦苦挣扎了一段时间。我发现 insert()enter() 选择的行为可以解决问题。这是基于其插入或附加元素被合并到更新选择中的输入选择之间的交互,插入与输入选择的工作方式。文档中的相关位:

selection.enter()

… The enter selection merges into the update selection when youappend or insert.

selection.insert()

… For enter selections, the before selector may be omitted, in whichcase entering elements will be inserted immediately before the nextfollowing sibling in the update selection, if any. This allows you toinsert elements into the DOM in an order consistent with bound data.

结果是,如果你将一些dt元素插入到enter selection中,它们将被合并到update selection中。然后,如果您随后将一些 dd 元素插入到输入选择中,它们将“立即插入到更新选择中的下一个兄弟元素之前”;也就是说,他们将在其关联的 dt 之后

var data = { a: 1, b: 2, c: 3 };
var dl = d3.select("body").append("dl").selectAll().data(Object.keys(data));
dl.enter().insert("dt").text(function(key) { return key });
dl.enter().insert("dd").text(function(key) { return data[key] });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

关于html - 如何使用 d3.js 创建定义列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24116328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com