我有一张随机排列的卡片清单。我无法弄清楚如何用这个乱序的列表替换现有的卡板。
let card_source = document.querySelectorAll('li.card');
let icon_class_list = [];
let card_list = [];
for (let i of card_source) {
card_list.push(i);
}
for (let icon_class of card_list){
icon_class_list.push(icon_class.lastElementChild)
}
// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
let shuffled = shuffle(icon_class_list);
for (let card_icon_space of card_source) {
for (let card_item of shuffled) {
card_icon_space.classList.replace('card_icon_space.children[0]', 'card_item');
}
}
<ul class="deck">
<li class="card">
<i class="fa fa-diamond"></i>
</li>
<li class="card">
<i class="fa fa-paper-plane-o"></i>
</li>
<li class="card">
<i class="fa fa-anchor"></i>
</li>
<li class="card">
<i class="fa fa-bolt"></i>
</li>
<li class="card">
<i class="fa fa-cube"></i>
</li>
</ul>
预期结果:现有的纸牌板现在有所不同,但牌面已改组。 实际:没有区别
答案 0 :(得分:0)
不是使用className而是使用DOM并将每个标签视为DOM对象。在演示中,“ ghost”文档是一个documentFragment,用于保留改组后的<li>
,直到使用{{3}清除<ul>
的“旧” <li>
}}。诚然,这似乎有些矫kill过正,但是无论您拥有多少<li>
,它都不会降低速度。演示中有详细评论。
// Reference <ul>
const deck = document.querySelector('.deck');
// Create a "ghost" document
let newDeck = document.createDocumentFragment();
// Collect <li> into a NodeList and convert to array
const unshuffled = [...deck.querySelectorAll('.card')];
// Copy the array
let cards = [...unshuffled];
// shuffle() new array
let shuffled = shuffle(cards);
// Add each <li> from new array to 'ghost' deck
for (let card of shuffled) {
newDeck.appendChild(card);
}
// Clear <li> from <ul>
let oldCards = document.createRange();
oldCards.selectNodeContents(deck);
oldCards.deleteContents();
// Add 'ghost' deck to <ul>
deck.appendChild(newDeck);
// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
<link href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" rel="stylesheet" crossorigin="anonymous">
<ul class="deck">
<li class="card">
<i class="far fa-star"></i>
</li>
<li class="card">
<i class="far fa-paper-plane"></i>
</li>
<li class="card">
<i class="fas fa-anchor"></i>
</li>
<li class="card">
<i class="fas fa-bolt"></i>
</li>
<li class="card">
<i class="fas fa-cube"></i>
</li>
</ul>