d3.js - 如何插入新的兄弟元素 [英] d3.js - how to insert new sibling elements

查看:75
本文介绍了d3.js - 如何插入新的兄弟元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在向现有元素插入新同级时遇到问题.

I have a problem with inserting new siblings to existing elements.

我有这个结构

<svg> 
  <g> 
    <path class="data"></path> 
    <path class="data"></path> 
  </g>
</svg>

想要这个结构

<svg> 
  <g> 
    <path class="data"></path> 
    <text></text>
    <path class="data"></path> 
    <text></text>
  </g>
</svg>

但是如果我使用 d3.js 插入函数

but if I use the d3.js insert function

d3.select("g").insert("text", "path.data");

我得到以下(尽管按类名选择)

i get the following (despite selecting by class name)

<svg> 
  <g> 
    <text></text>
    <path class="data"></path> 
    <path class="data"></path> 
  </g>
</svg>

有什么想法吗?

推荐答案

首先,值得注意的是,插入函数中的第二个参数是一个 before 选择器.此外,链式操作作用于左手结果.

First of all, it's worth noting that the second argument in the insert function is a before selector. Furthermore, chained operations act on the left hand result.

你已经完成了

// select all the g elements (only 1)
d3.select("g")
    // For each g, insert a text element before "path.data"
    .insert("text", "path.data");

您想对每个子.data"执行一个操作,因此您需要选择每个.data"元素并为每个元素执行一个操作.我不完全确定 d3 如何期望您在特定子项之后插入元素.我发现使用 DOM API 来创建和插入元素要容易得多,但使用 d3.each 函数来迭代选择.

You want to perform an operation for each child ".data", so you need to select each of the ".data" elements and perform an action for each of them. I'm not entirely sure how d3 expects you to insert an element after a specific child. I find it much easier to use the DOM API to do the element creation and insertion, but using the d3.each function to iterate over a selection.

d3.selectAll("g > .data").each(function () {
    var t = document.createElement('text');
    this.parentNode.insertBefore(t, this.nextSibling);       
});​

这篇关于d3.js - 如何插入新的兄弟元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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