Javascript 将相同的属性设置到所选元素javascipt

Javascript 将相同的属性设置到所选元素javascipt,javascript,Javascript,我的代码: const useElem = []; for (var a = 1; a <= 24; ++a) { useElem[a] = document.createElementNS('http://www.w3.org/2000/svg', 'use'); } useElem[1].setAttribute( 'class', 'normal'); useElem[2].setAttribute( 'class', 'normal'); useElem[1].setAtt

我的代码:

const useElem = [];
for (var a = 1; a <= 24; ++a) {
    useElem[a] = document.createElementNS('http://www.w3.org/2000/svg', 'use');
}
useElem[1].setAttribute( 'class', 'normal');
useElem[2].setAttribute( 'class', 'normal');
useElem[1].setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', url_normal_1);
useElem[2].setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', url_normal_2);
useElem[3].setAttribute( 'class', 'hover');
useElem[4].setAttribute( 'class', 'hover'); 
useElem[3].setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', url_hover_1);
useElem[4].setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', url_hover_2);   
useElem[5].setAttribute( 'class', 'active');
useElem[6].setAttribute( 'class', 'active');    
useElem[5].setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', url_active_1);
useElem[6].setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', url_active_2);
.......

有很多方法可以减少代码重复,例如,如果不想使用循环,也可以使用helper函数:

function createElement(clas, url) {
  const el = document.createElementNS("http://www.w3.org/2000/svg", "use");
  el.setAttribute("class", clas);
  el.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", url);
  return el;
}

const useElem = [
    null, // to start arrays at 1 O_o
    createElement('normal', url_normal_1),
    createElement('normal', url_normal_2),
    createElement('hover', url_hover_1),
    createElement('hover', url_hover_2),
    createElement('active', url_active_1),
    createElement('active', url_active_2),
    // ...
]

有很多方法可以减少代码重复,例如,如果不想使用循环,也可以使用helper函数:

function createElement(clas, url) {
  const el = document.createElementNS("http://www.w3.org/2000/svg", "use");
  el.setAttribute("class", clas);
  el.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", url);
  return el;
}

const useElem = [
    null, // to start arrays at 1 O_o
    createElement('normal', url_normal_1),
    createElement('normal', url_normal_2),
    createElement('hover', url_hover_1),
    createElement('hover', url_hover_2),
    createElement('active', url_active_1),
    createElement('active', url_active_2),
    // ...
]

你可以更多地利用循环这正是我想要避免的为什么?您已经有了一个循环,可以用于purposes@Serg为什么要避免循环?它应该减少重复;a你可以更多地利用漏洞,这正是我想要避免的。为什么?您已经有了一个循环,可以用于purposes@Serg为什么要避免循环?它应该减少重复;A.