Javascript:如何将SVG图像放入数组?
假设我有三个圆圈——一个红色,一个黄色和一个绿色Javascript:如何将SVG图像放入数组?,javascript,arrays,svg,Javascript,Arrays,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="5
<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个元素的数组?
如果没有,你能推荐一种方法我可以创建一个数组,其中包括三个圆圈,红色,黄色和绿色
非常感谢
<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>
为您演示(检查控制台)
document.queryselectoral('svg')代码>或文档。getElementsByTagName('svg')
可用于将所有svg
元素放入类似数组的对象中
document.querySelectorAll()
将在
document.getElementsByTagName(“”)
将返回HTMLCollection
1-创建父SVG元素
2-将数据绑定到svg并输入()
如果在数组中需要它们,首先获取它们的父元素。让我们称之为svgParent
,然后这样做
var svgArr = Array.prototype.slice.call(svgParent.querySelectorAll("svg"));
您应该将这三个svg元素放在一个适当的数组中。我们从父级使用element.querySelectorAll()
,因为如果存在其他svg元素,我们不希望收集这三个元素以外的svg元素。元素的语法被破坏(…width“100”=“”…
)。var svgImages=document.querySelectorAll('svg')
当你说“你有3个圆圈”时,你的意思是它们在呈现的html页面(内联)中,作为某些html/xml中的链接目标,还是以文本形式在(JS)字符串中?@collapsar以文本形式在JS字符串中。querySelectorAll
返回NodeList
这是类似于对象的数组。。不是array
。类似数组的对象有什么问题?或者,如果@DragonSlayer不知道如何查找DOM元素,您认为获得真正的数组非常重要吗?LOL@AndrewEvt我已经在DOM元素中有了它。我的问题是我是否可以将其包含在数组中。问题没有标记为D3对不起,我是新来的。
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"]; });
var svgArr = Array.prototype.slice.call(svgParent.querySelectorAll("svg"));