循环元素不起作用
Looping through elements is not working
我正在尝试为网页上的每个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);
相关文章:
- 在IE8中不起作用的元素上触发单击事件
- 删除不起作用的父元素和所有子元素
- 更改第二次推送时不起作用的元素高度
- 为什么body元素上的onclick事件不起作用
- iframe中的jQuery查找元素不起作用
- jQuery选择ajax调用中附加的元素不起作用
- JQuery-动态创建的元素css不起作用
- angular元素在通过ng类添加类时不起作用
- 当我动态创建元素时,选择的插件不起作用
- .clone().appendTo-替换不起作用的元素样式
- 我的ID获取元素不起作用
- Javascript - 当使用 Javascript 生成 HTML 元素时,Magnific Popup 不起作用
- HTML 显示/隐藏元素 JS 不起作用
- 悬停时函数在具有相同 id 的多个元素中不起作用
- jQuery Ajax 元素的后期绑定不起作用
- 转换元素在引导程序中不起作用
- 为什么从 Angular 服务中的对象中删除此元素不起作用
- colorbox与元素实时绑定'分组获胜'不起作用
- 剑道模板在元素中单击不起作用
- 使用jQuery隐藏元素;不起作用