簡體   English   中英

每第 n 個數組元素創建一個新的 div 並附加項目

[英]Create a new div every nth array element and append item

我有一個元素數組。 我想要的是策略性地將元素添加到 div 中。 首先,添加類.wrapperItems然后從數組中只添加 5 個元素,然后如果數組中還有更多元素,則創建一個新的.wrapperItems div 並附加剩余的數組元素。 循環直到所有數組元素都被追加。 我怎樣才能做到這一點? 提前致謝。

看看我下面的 HTML 代碼,了解我想要的結構是什么樣的。

*該解決方案必須適用於任何數組長度!

 let myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9'] $('.wrapper .wrapperItems').html('') myArray.forEach((elm) => { //add only 5 "itemCon" then create new ".wrapperItems" $('.wrapper .wrapperItems').append(`<div class="itemCon"><p>${elm}</p></div>`) })
 .wrapper { display: flex; flex-direction: column; width: 100%; height: fit-content; background-color: gold; } .wrapperItems { display: flex; flex-direction: row; justify-content: center; width: 100%; height: fit-content; background-color: coral; } .itemCon { display: flex; width: 15%; height: 7vh; background-color: pink; } .itemCon p { margin: auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <div class="wrapperItems"> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> </div> <div class="wrapperItems"> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> <div class="itemCon"> <p>test</p> </div> </div> </div>

這實際上是一個關於如何將數組分塊為數組數組的問題。

這可以通過映射和分組來完成。

 let myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9','test10','test11']; const result = Object.values( myArray.map( (x,i) => ({grp:Math.floor(i/5),val:x})) .reduce((acc,i) => { acc[i.grp] ||= []; acc[i.grp].push(i.val); return acc; },{}) ); console.log(result);

那時,它只是外部數組上的forEach問題,其中每個元素將是(最多)5個項目的數組

 let myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9'] const result = Object.values( myArray.map( (x,i) => ({grp:Math.floor(i/5),val:x})) .reduce((acc,i) => { acc[i.grp] ||= []; acc[i.grp].push(i.val); return acc; },{}) ); result.forEach((elm) => { //add only 5 "itemCon" then create new ".wrapperItems" const $wrapperItems = $("<div>").addClass("wrapperItems"); elm.forEach(item => { $wrapperItems.append(`<div class="itemCon"><p>${item}</p></div>`) }); $(".wrapper").append($wrapperItems); })
 .wrapper { display: flex; flex-direction: column; width: 100%; height: fit-content; background-color: gold; } .wrapperItems { display: flex; flex-direction: row; justify-content: center; width: 100%; height: fit-content; background-color: coral; } .itemCon { display: flex; width: 15%; height: 7vh; background-color: pink; } .itemCon p { margin: auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> </div>

首先,將您的數組分解為 5 個塊。

const chunkSize = 5;

function chunkify(arr, size) {
  for (let i = 0; i < arr.length; i++) {
    let toSplice = arr.splice(i, size);
    arr.unshift(toSplice);
  }
  return arr.reverse();
}

然后遍歷分塊數組以獲得所需的輸出。

const myArray = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9']

const chunkedArray = chunkify(myArray, chunkSize);

const $parentEl = $('.wrapper');

chunkedArray.forEach((arr) => {
  const $wrapper = $('<div/>', { 'class': 'wrapperItems' });
  arr.forEach(item => {
    const $itemCon = $('<div/>', { 'class': 'itemCon' });
    const $p = $('<p/>', { text: item });
    $itemCon.append($p);
    $wrapper.append($itemCon);
  });
  $parentEl.append($wrapper);
});

這是一個循環遍歷數組中的項目並在每次完成每個“切片”時為新創建的相應 div 創建一個新容器的解決方案。

考慮到您只需要訪問輸入數據的每個節點並相應地執行操作,因此在選擇要執行的操作時,無需為了接近分組事后而創建添加的數據結構。

我想不出比這更易讀、更有效的方法:

 let items = [ 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9' ]; const slice = 5; const target = $('#wrapper'); let currentGroup; let itemCounter = 0; for(const item of items){ if (itemCounter++ % slice == 0) { currentGroup = $('<div></div>').addClass("wrapperItems"); $(target).append( currentGroup ); } $(currentGroup).append( $('<div></div>').addClass("itemCon") ); }
 .wrapper { display: flex; flex-direction: column; width: 100%; height: fit-content; background-color: gold; } .wrapperItems { display: flex; flex-direction: row; justify-content: center; width: 100%; height: fit-content; background-color: coral; border: solid blue 1px; } .itemCon { display: flex; width: 15%; height: 7vh; background-color: pink; border: solid red 1px; } .itemCon p { margin: auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="wrapper"> </div>

 const datas = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9']; // divide data by length const divide = (arr, n) => arr.reduce((r, e, i) => (i % n ? r[r.length - 1].push(e) : r.push([e])) && r, []); // generate content according to given data and length const generate = (arr, n) => { const groups = divide(arr, n); for (const group of groups) { // convert the divided data into an array of elements const $content = group.map(s => $('<div>', { class: 'itemCon' }).append($('<p/>', { text: s }))); //add items, fill in content, add to wrapper const $wrapperItems = $('<div>', { class: 'wrapperItems' }).append($content).appendTo($('.wrapper')); } }; // call and use method generate(datas, 5);
 .wrapper { display: flex; flex-direction: column; width: 100%; height: fit-content; background-color: gold; } .wrapperItems { display: flex; flex-direction: row; justify-content: center; width: 100%; height: fit-content; background-color: coral; } .itemCon { display: flex; width: 15%; height: 7vh; background-color: pink; } .itemCon p { margin: auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> </div>

暫無
暫無

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

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