簡體   English   中英

根據數組元素的排序對 DOM 元素進行排序

[英]Sort DOM elements based on the sorting of the array elements

我有 3 個 HTML 元素和一個包含 3 個元素的數組。

 const args = ['Red', 'Purple', 'Green'];
 .box { width: 100%; height: 100px; color: #fff; border: 1px solid #fff; padding: 10px; }.green { background: green; }.red { background: red; }.purple { background: rebeccapurple; }
 <div class="box green">1</div> <div class="box red">2</div> <div class="box purple">3</div>

我想根據數組中元素的索引對 DOM 中的 HTML 元素進行排序。 因此,例如,如果數組是['Red', 'Purple', 'Green'] ,則紅色框應在頂部,紫色在中間,綠色框在底部。 我怎樣才能做到這一點?

像這樣:

 const container = document.getElementById("container"); ['Red', 'Purple', 'Green'].forEach(col => container.appendChild(container.querySelector("." + col.toLowerCase())))
 .box { width: 100%; height: 100px; color: #fff; border: 1px solid #fff; padding: 10px; }.green { background: green; }.red { background: red; }.purple { background: rebeccapurple; }
 <div id="container"> <div class="box green">1</div> <div class="box red">2</div> <div class="box purple">3</div> </div>

如果多個div具有相同的class

 const container = document.getElementById("container"); ['Red', 'Purple', 'Green'].forEach(col => container.querySelectorAll("." + col.toLowerCase()).forEach(div => container.appendChild(div)))
 .box { width: 100%; height: 100px; color: #fff; border: 1px solid #fff; padding: 10px; }.green { background: green; }.red { background: red; }.purple { background: rebeccapurple; }
 <div id="container"> <div class="box green">1</div> <div class="box red">2</div> <div class="box purple">3</div> <div class="box red">4</div> </div>

 const args = ['Red', 'Purple', 'Green'].map(arg => arg.toLowerCase()); let divs = document.querySelectorAll('div.box'); let sortedDivs = Array.from(divs).sort((a, b) => { aClass = Array.from(a.classList).filter(clas => args.indexOf(clas) > -1)[0]; bClass = Array.from(b.classList).filter(clas => args.indexOf(clas) > -1)[0]; return args.indexOf(aClass) - args.indexOf(bClass); }); sortedDivs.forEach(div => { document.body.appendChild(div); });
 .box { width: 100%; height: 100px; color: #fff; border: 1px solid #fff; padding: 10px; }.green { background: green; }.red { background: red; }.purple { background: rebeccapurple; }
 <div id="container"> <div class="box green">1</div> <div class="box red">2</div> <div class="box purple">3</div> <div class="box red">4</div> </div>

暫無
暫無

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

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