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

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

问题描述

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

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.

推荐答案

selection.append() 函数接受以下两种类型之一:

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

  • 一个字符串,它是要创建的元素的名称,或者
  • 一个函数,它被执行(应用于父级)并且应该返回一个元素或 HTML.
  • 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.

如果您使用

var newElem = document.createElement(tagname);

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

并且您想将该新元素添加到您的 d3 选择中,那么您可以使用:

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

mySelection.node().appendChild(newElem)

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

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.

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

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

但是请注意,您不能在普通元素上使用 d3 的任何魔法,除非您将它们包装在 d3.select(elem) 中.

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

假设您有两个选择 s1s2,并且您希望将 s2 附加到 s1.如果两者分别只对一个元素进行选择,那么您可以简单地使用

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

s1.append(function() {return s2.node()})

如果 s1 和/或 s2 是对多个元素的选择,您需要先遍历两个选择并使用

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

s1.append(function() {return s2[i].node()})

相反.

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

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