2016-04-27 159 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

對不起,我這裏是新的。 –