将DOM元素附加到D3 [英] Append DOM element to the D3

查看:151
本文介绍了将DOM元素附加到D3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用D3在SVG上绘图。我想要的是将DOM元素或HTML附加到D3,如:

  task.append(function(model){
//这里返回html或dom
};



<但是很遗憾,我找不到任何示例或找不到如何自己这样做。

解决方案

selection.append接受以下两种类型之一:




  • 一个字符串,它是要创建的元素的名称, li>
  • 执行(应用于父级)并应返回元素或HTML的函数




将自定义创建的元素添加到d3选择

h1>

如果您使用

创建了元素。

  var newElem = document.createElement tagname); 

  var newElem = document.createElementNS(d3.ns.prefix.svg,tagname); 

,并且要将该新元素添加到d3选择中,则可以使用:

  mySelection.node()appendChild(newElem)

这将基本上将新元素附加到您选择的第一节点。要从选择中将元素附加到每个节点,您需要对每个单个项目上的mySelection和调用节点()进行循环。



添加多个自定义创建的元素工作原理相同,但您可以使用 element.cloneNode(true)



保存您自己的一些工作

不能使用任何d3的魔术对普通元素,除非你包装在 d3.select(elem)



< h1>将d3选择添加到d3选择



我们假设您有两个选择 s1 s2 想要s2附加到s1。如果两者都只是一个元素的选择,那么你可以简单地使用

  s1.node()。appendChild(s2.node ())

如果s1和/或s2是多个元素的选择,选项,然后改用 s1 [i] .node()。append(s2 [j] .node())


I'm using D3 for drawing on the SVG. What I want is to append DOM element or HTML to the D3, like:

task.append(function(model){
//here return html or dom
};

Documentation says it's possible, but unfortunately I can't find any example or found out how to do this myself.

解决方案

The selection.append() function accepts one of two types:

  • A string which is the name of an element to create, or
  • A function which is executed (applied on parent) and should return an element or HTML.

Your question wasn't very specific, so I'll do a wild guess here.

Appending custom created elements to a d3 selection

If you created your element using

var newElem = document.createElement(tagname);

or

var newElem = document.createElementNS(d3.ns.prefix.svg, tagname);

and you want to add that new element to your d3 selection then you can use this:

mySelection.node().appendChild(newElem)

This will basically append the new element to the first node from your selection. For appending the element to every node from the selection you'd need to make a loop over mySelection and call node() on every single item.

Adding multiple custom created elements works the same, but you can save yourself some work using element.cloneNode(true)

Note however that you can't use any of d3's magic on plain elements, except you wrap them in d3.select(elem).

Appending a d3 selection to a d3 selection

Let's assume you have two selections s1 and s2 and you want s2 to be appended to s1. If both are selections over only one element respectively, then you can simply use

s1.node().appendChild(s2.node())

If s1 and/or s2 are being selections over multiple elements you need to iterate over both selections first and use s1[i].node().append(s2[j].node()) instead.

这篇关于将DOM元素附加到D3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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