循环使用元素无效

时间:2015-11-03 18:56:01

标签: javascript for-loop svg path appendchild

我正在尝试为网页上的每个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();

 }
&#13;
<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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分: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]);
}

答案 1 :(得分:0)

相反

svg.appendChild(newElement);

尝试:

svg[i].appendChild(newElement);