[英]What is the correct way to loop through an HTML Collection
I am trying to make a slider, and while the code below to calculate the widths of the slides works, it throws an error in the console. 我正在尝试制作一个滑块,虽然下面的代码可以计算幻灯片的宽度,但它在控制台中引发了错误。 What is the correct way to loop through and a width to these elements?
循环遍历这些元素的正确方法是什么?
Javascript Java脚本
var calcSlideWidth = function(divId){
let slDiv = document.getElementById(divId);
let slides = slDiv.getElementsByClassName('slide');
slDiv.style = "width:"+ 100*slides.length +"%";
slideWidth = 100/slides.length;
for (let i = 0; i <= slides.length; i++ ){
slides[i].style = " width:"+ slideWidth +"%";
console.log(i);
}
}
window.onload = function(){
calcSlideWidth("slider");
}
HTML 的HTML
<div class="slider-container">
<ul id="slider">
<li class="slide"><span>Slide 1</span></li>
<li class="slide"><span>Slide 2</span></li>
<li class="slide"><span>Slide 3</span></li>
</ul>
</div>
The getElementsBy* methods return HTMLCollections, which can be difficult to work with. getElementsBy *方法返回HTMLCollections,这可能很难使用。 Consider using querySelectorAll instead, which returns a static NodeList - unlike an HTMLCollection, it can be iterated over directly, it won't change while it's being iterated over, and it's much more flexible.
考虑改用querySelectorAll,它返回一个静态NodeList -与HTMLCollection不同,它可以直接进行迭代,在进行迭代时不会更改,并且更加灵活。
document.querySelectorAll('.slide').forEach(slide => {
// do stuff with each slide
slide.style.width = `${slideWidth}%`;
});
for
loops fail to clearly signal the intention of your code, and as such should be avoided whenever possible (prefer higher-order functions, such as .map, .reduce, .filter, ...). for
循环无法清楚地表明您的代码意图,因此应尽可能避免使用(最好使用高阶函数,例如.map,.reduce,.filter等)。 See also: http://qr.ae/RNMEGA and https://gist.github.com/robotlolita/7643014 另请参阅: http : //qr.ae/RNMEGA和https://gist.github.com/robotlolita/7643014
(you'll never have an off-by-one error through .forEach
) (通过
.forEach
您将永远不会出现一个错误的错误)
Note that NodeList.forEach is a new-ish method that some older browsers don't support - if you use this method, make sure to polyfill properly before distribution. 请注意,NodeList.forEach是一些较旧的浏览器不支持的新方法-如果使用此方法,请确保在分发之前正确地填充。
The error for sure is the access at position length
确定的错误是位置
length
处的访问
let i = 0; i <= slides.length
^
That condition will access to a none existing position, so you need to use this: 该条件将访问一个不存在的职位,因此您需要使用以下条件:
let i = 0; i < slides.length
^
That way, the access will be from 0
until length - 1
这样,访问将从
0
到length - 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.