如何更有效地将不同类名的元素保存在单独的变量中?

问题描述 投票:0回答:1

在我的程序中,我以经典的方式将元素保存在每个变量中。但是元素多的时候,代码行也多。有没有更有效的方法?

  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');
javascript class variables
1个回答
0
投票

您可以将所有类放在一个数组中,然后循环遍历这些类:

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];
....
© www.soinside.com 2019 - 2024. All rights reserved.