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

查看:1621
本文介绍了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>

任何想法?

推荐答案

首先,值得注意的是,插入函数中的第二个参数是之前选择器。

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