2015-11-03 195 views
0

我想爲網頁上的每個SVG添加一條額外的路徑。我設置了我的for循環,它正在工作,但一旦它循環通過它告訴我appendChild()不是一個函數。如果我把所有的東西都拿出來循環appendChild()的作品。我在這裏做錯了什麼?通過元素循環不起作用

var svg = document.getElementsByClassName('curve-position-bottom'); //Get svg element 
 
for (var i = 0; i < svg.length; i++) { 
 
    console.log(svg.length); 
 

 
    function addPath() { 
 
    console.log('working'); 
 
    var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace 
 
    newElement.setAttribute("d", "M0 0 C50 100 50 100 100 0 "); //Set path's data 
 
    newElement.style.stroke = "#005780"; //stroke colour 
 
    newElement.style.strokeWidth = "13px"; //Set stroke width 
 
    newElement.style.fill = "none"; //Set stroke width 
 
    svg.appendChild(newElement); 
 
    } 
 
    addPath(); 
 

 
}
<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 100 100" version="1.1" preserveAspectRatio="none" height="45px" class="engle-curve curve-position-bottom" style="fill:#e6e2af"> 
 
    <path stroke-width="0" d="M0 0 C50 100 50 100 100 0 L100 100 0 100"></path> 
 
</svg> 
 

 
<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 100 100" version="1.1" preserveAspectRatio="none" height="45px" class="engle-curve curve-position-bottom" style="fill:#e6e2af"> 
 
    <path stroke-width="0" d="M0 0 C50 100 50 100 100 0 L100 100 0 100"></path> 
 
</svg> 
 

 
<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 100 100" version="1.1" preserveAspectRatio="none" height="45px" class="engle-curve curve-position-bottom" style="fill:#e6e2af"> 
 
    <path stroke-width="0" d="M0 0 C50 100 50 100 100 0 L100 100 0 100"></path> 
 
</svg>

回答

2

document.getElementsByClassName返回值是一個NodeList,而不是一個單獨的元素。要使用您定義的SVG,您需要使用svg[i]


此外,無關你的問題,但它會以移動函數定義出循環(對於性能和範圍的原因),並把它與SVG元素作爲參數調用一個好主意。它看起來更像這樣:

var svg = document.getElementsByClassName('curve-position-bottom'); //Get svg elements 

function addPath(svg) { 
    console.log('working'); 
    var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace 
    newElement.setAttribute("d", "M0 0 C50 100 50 100 100 0 "); //Set path's data 
    newElement.style.stroke = "#005780"; //stroke colour 
    newElement.style.strokeWidth = "13px"; //Set stroke width 
    newElement.style.fill = "none"; //Set stroke width 
    svg.appendChild(newElement); 
} 

for (var i = 0, length = svg.length; i < length; i++) { 
    addPath(svg[i]); 
} 
0

相反

svg.appendChild(newElement); 

嘗試:

svg[i].appendChild(newElement);