我只是想用一类搜索音频将一个 div 与幻灯片类包裹在每 3 个 div 周围。
我遇到的一个错误是它说 elem.parentElement 未定义...
所以这部分效果很好......
const audioBlocks = document.querySelectorAll('.search-audio');
const slider = document.querySelector('.slider');
const audioBlockArr = Array.from(audioBlocks);
function groupBlocks(arr, len) {
let groups = [],
i = 0,
n = arr.length;
while (i < n) {
groups.push(arr.slice(i, i += len));
}
return groups;
}
newArr = [...groupBlocks(audioBlockArr, 3)];
问题就在这里 - 将一个 div 包裹在新的分组元素数组周围。
let wrap = (array) => {
array.forEach((elem) => {
let div = document.createElement('div');
div.classList.add('slide');
div.innerHTML = '';
elem.parentElement.insertBefore(div, elem);
div.appendChild(elem);
});
}
wrap(newArr);
完整代码:
const audioBlocks = document.querySelectorAll('.search-audio');
const slider = document.querySelector('.slider');
const audioBlockArr = Array.from(audioBlocks);
function groupBlocks(arr, len) {
let groups = [],
i = 0,
n = arr.length;
while (i < n) {
groups.push(arr.slice(i, i += len));
}
return groups;
}
newArr = [...groupBlocks(audioBlockArr, 3)];
let wrap = (array) => {
array.forEach((elem) => {
let div = document.createElement('div');
div.classList.add('slide');
div.innerHTML = '';
elem.parentElement.insertBefore(div, elem);
div.appendChild(elem);
});
}
wrap(newArr);
body {
font-family: system-ui;
background: #f06d06;
color: white;
text-align: center;
}
.search-audio {
height: 12rem;
width: 12rem;
background: rgb(255, 153, 0);
margin: .5rem;
display: inline-block;
}
.slide {
background-color: #555;
}