在我的程序中,我以经典的方式将元素保存在每个变量中。但是元素多的时候,代码行也多。有没有更有效的方法?
let el1 = document.getElementsByClassName('class-1');
let el2 = document.getElementsByClassName('class-2');
let el3 = document.getElementsByClassName('class-3');
let el4 = document.getElementsByClassName('class-4');
let el5 = document.getElementsByClassName('class-5');
let el6 = document.getElementsByClassName('class-6');
let el7 = document.getElementsByClassName('class-7');
let el8 = document.getElementsByClassName('class-8');
您可以将所有类放在一个数组中,然后循环遍历这些类:
let classNameArr = ['class-1', 'class-2', 'class-3', 'class-4', 'class-5', 'class-6', 'class-7', 'class-8'];
let elementArr = [];
classNameArr.forEach(cn => elementArr.push(document.getElementsByClassName(cn));
现在使用:
let el1 = elementArr[0];
let el2 = elementArr[1];
....