d3创建对象而不添加 [英] d3 create object without appending

查看:1575
本文介绍了d3创建对象而不添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用d3绘图,我正在尝试创建一个svg对象,以后添加到DOM。

I'm using d3 for graphing, and I'm trying to create an svg object, to add to the DOM later.

我以前有



I used to have

var svg = d3.select(el).append("svg");
var graph = svg.append("g")
...etc...

并且由于我不会进入,我想创建 svg 元素,然后将它添加到DOM。

and for reasons I won't go into, I wanted to create the svg element before appending it to the DOM.

所以我做了

var svg = d3.select(document.createElementNS(d3.ns.prefix.svg, 'svg'))
var graph = svg.append("g")
...etc...

,在调试时,我可以看到 svg 是一个1元素数组,

, which works, and while debugging, I can see that svg is a 1-element array, with the children nicely attached.

问题出现在 append 步骤:

d3.select(el).append(svg);

这里,我收到一个错误错误:无法执行'createElementNS' 'document':提供的限定名('[object SVGSVGElement]')包含无效的名字 - 起始字符'['。我看看这里:如何创建svg对象没有附加它?但它似乎是他们建议它是什么。

There, I get an error Error: Failed to execute 'createElementNS' on 'Document': The qualified name provided ('[object SVGSVGElement]') contains the invalid name-start character '['. I've taken a look here: How to create "svg" object without appending it? but it seems that's exactly how they suggest it.

任何想法为什么会这样?我试过追加 svg [0] ,但也没有运气。似乎 append()只接受字符串作为参数。

Any idea why this is so? I've tried appending svg[0], but no luck either. It seems append() only takes strings as an argument.

编辑: https://github.com/mbostock/d3/wiki/上的d3参考选择#追加个州


selection.append(name)
... ... ...
该名称可以指定为常量字符串或返回要追加的DOM元素的函数。

selection.append(name) ... ... ... "The name may be specified either as a constant string or as a function that returns the DOM element to append."

因此,我试过了

d3.select(el).append(function(){return svg;});

但是失败并出现错误:无法对'appendChild'节点':新的子元素为空。

推荐答案

如果 svg 是一个选择, svg.node()返回DOM元素,例如:

If svg is a selection, svg.node() returns the DOM element, e.g.:


d3.select(el).append(function(){return svg.node();});

(注意,我不确定 svg 在你的情况是一个真正的选择,但你可以试试。)

(Mind you, I'm not certain that svg in your case is a true selection, but you could give it a try.)

这篇关于d3创建对象而不添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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