簡體   English   中英

向存儲在數組中的元素添加類的更簡潔的方法?

[英]More concise way of adding a class to elements stored in an array?

我創建了3個元素,稍后在我的代碼中,我需要向每個元素添加相同的類。 目前,我正在這樣做,並且工作正常:

const item1 = document.createElement('div');
const item2 = document.createElement('div');
const item3 = document.createElement('div');

// later on in the code

function addClasses() {
  item1.classList.add('item--animating');
  item2.classList.add('item--animating');
  item2.classList.add('item--animating');
}

但是,似乎沒有這種重復。 有沒有更短的書寫方式?

我可以創建一個項目數組,然后遍歷該數組,向每個對象添加類,但是我認為這在使代碼簡潔且易於推理方面會適得其反。

擴展Rajesh的答案:

const item1 = document.createElement('div');
const item2 = document.createElement('div');
const item3 = document.createElement('div');
const allItems = [item1, item2, item3];

allItems.forEach(x => x.classList.add('item--animating'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM