循环元素不起作用

Looping through elements is not working

本文关键字:不起作用 元素 循环      更新时间:2023-09-26

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

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]);
}

替代

svg.appendChild(newElement);

尝试:

svg[i].appendChild(newElement);