我可以用d3附加一个文字SVG元素吗? [英] Can I append a literal SVG element with d3?

查看:84
本文介绍了我可以用d3附加一个文字SVG元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用d3附加一个文字SVG元素。

I'd like to append a literal SVG element with d3.

所以不要写

svg.selectAll("circle")            
    .data(data)                    
    .enter()                       
    .append("circle")    // etc etc

我想这样做:

svg.selectAll("circle")            
    .data(data)                    
    .enter()                       
    .append('<circle cx="158.9344262295082" cy="200" r="16" fill="red"></circle>')   

这样我就可以在别处创建一个复杂的模板(例如使用把手),然后用数据编译并附加它。

so that I could create a complex template elsewhere (for example with handlebars), and then compile it with data and append it.

推荐答案

你可以这样做,虽然不是通过 selection.append()功能。相反,您需要使用 selection.html() function。

You can do this, although not via the selection.append() function. Instead you'd need to use the selection.html() function.

这会使得在数据连接的上下文中使用起来非常困难,但并非不可能。这可能是你可以做的最好的,这涉及到DOM添加一个额外的svg组,这可能不是一件坏事:

This would make it quite difficult to use in the context of data-joins, but not impossible. This is probably the best you could do, which involves adding an additional svg group to the DOM which may not be a bad thing anyway:

var svg = d3.selectAll("svg");
svg.selectAll("circle")            
       .data([50, 100, 150])                    
       .enter()                       
       .append("g")
       .attr("transform", function(d) { return "translate(" + [d, d] + ")"; })
       .html('<circle r="16" fill="red"></circle>');   

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="500"></svg>

我想这个答案更进一步,你可以实际嵌入结果您希望直接呈现到数据对象中。所以你添加了一些看起来像的代码:

I guess taking this answer a bit further, you could actually embed the result that you wish to render directly into your data object. So you've add some code that looked like:

.html(function(d){return d.templatedHTML;});

此时请停下来问自己一个问题:我用D3做什么用途?。 D3被描述为

At this point however stop and ask yourself the question: "What am I using D3 for?". D3 is described as


数据驱动文档

Data Driven Documents



<如果您正在使用像把手这样的东西,那么您将剥夺D3为其设计的核心职责之一(从某些数据构建一些DOM)并将其交给其他库。

If you're using something like handlebars, then you're taking away one of the core responsibilities that D3 was designed for (building some DOM from some data) and giving it to some other library.

我不是说你不应该这样做(正如你提到的那样复杂的模板)但是要问问自己这个问题,以确保它是你想要的路径下来。

I'm not stating you shouldn't do that (as you did mention complex templates) but do just ask yourself the question to make sure that it's a path you wish to go down.

这篇关于我可以用d3附加一个文字SVG元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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