2016-04-27 63 views
-2

假设我有三个圈 - 一个红色,一个黄色和一个绿色。Javascript:如何将SVG图像放入数组中?

<svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="red "></circle> </svg> 

    <svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="yellow"></circle> </svg> 

    <svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="green"></circle> </svg> 

是否有可能创建一个包含这3个数组的数组? 如果不是,你能推荐一种方法来创建一个包含三个红色,黄色和绿色圆圈的数组吗?

非常感谢

+0

元素的语法被破坏('... width“100”=“”...')。 – collapsar

+0

'var svgImages = document.querySelectorAll('svg');' –

+0

当你说'你有3个圈子'时,你的意思是你有他们在一个HTML页面(内联),作为一些html/xml中的链接目标,或者在(JS)字符串中的文本? – collapsar

回答

0

如果您在数组中需要它们,请首先获取它们的父元素。我们称之为svgParent然后这样做。

var svgArr = Array.prototype.slice.call(svgParent.querySelectorAll("svg")); 

你应该得到三个svg元素在一个适当的数组中。我们使用父母的element.querySelectorAll(),因为如果存在其他的svg元素,我们不想收集这三个以外的svg元素。

0
<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="red "></circle> </svg> 

    <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="yellow"></circle> </svg> 

    <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="green"></circle> </svg> 

JS代码

var svgArray = document.querySelectorAll('svg'); 

console.log(svgArray[0]); // svgArray[0] is red circle 

https://jsfiddle.net/b9mysaew/演示给你(检查控制台)

+0

'querySelectorAll'返回的'NodeList'是'类似数组的对象..而不是'数组'' – Rayon

+0

和类似数组的对象有什么问题?或者你认为对于@DragonSlayer来说,如果他不知道如何查找DOM元素,那么获得一个真正的“数组”是非常重要的?大声笑 –

+0

@AndrewEvt我已经在一个DOM元素。我的问题是我是否可以将它包含在一个数组中。 – DragonSlayer

0

document.querySelectorAll('svg');document.getElementsByTagName('svg')可以用把所有的svg元素就像一个数组目的。

document.querySelectorAll()将返回一个NodeList

document.getElementsByTagName('')将返回HTMLCollection

0

1-创建一个父SVG元素

2-数据绑定到SVG和输入()

var svg = d3.select("body").append("svg") 
    .attr("width", width + margin.left + margin.right) 
    .attr("height", height + margin.top + margin.bottom + 20); 

var circles = svg.selectAll(".month") 
    .data(eachcircle); 
//loop from 0 to eachcircle.length 
circlesdata(eachcircle).append("circle") 
    .attr("cx", function(d,i) { return d[["x"];}) 
    .attr("cy", function(d,i) { return d["y"];}) 
    .attr("r", function (d) { return d["r"]; }) 
    .style("fill", function(d) { return d["color"]; }); 
+0

这个问题没有标记为d3 –

+0

对不起,我这里是新的。 –