我能够完成这项工作,但我相信我在这里确实使这项工作变得非常肮脏。我想知道,是否有更简单的方法来做到这一点。我是出于学习目的。
Fetch正在提取json对象,并且对象中具有一个图像数组,然后使用图像填充其自身容器中的内容。我试图使用上一个和下一个按钮在图像之间切换。
每个容器可容纳4或5个不同的图像。
这是我的代码。我试图坚持使用ES6。我不想在这个上使用jquery。
fetch('./public/js/projects.json')
.then((Response) => {
return Response.json();
}).then((data) => {
const projects = data.projects;
projects.map((project, index) => {
const container_projects = document.getElementById('projects');
const project_img = project.img
const markup_project = `
<div class="project" aria-label="${index}">
<div class="project_image">
<div class="arrow_container">
<button class="arrows left_arrow"><img src="assets/svg/left_arrow.svg" class="left"/></button>
<div class="numbers">
<span class="current">1</span>
<span class="divider">/</span>
<span class="total">${project_img.length}</span>
</div>
<button class="arrows right_arrow"><img src="assets/svg/right_arrow.svg" class="right"/></button>
</div>
<div class="image_container">
${project_img.map(image => `<img src="${image}" class=""/>`).join('')}
</div>
</div>
<small class="project_name">${project.title}</small>
</div>
`
container_projects.innerHTML += markup_project;
})
return projects
}).then((data) => {
data.map((project, index) => {
const current_project = document.querySelectorAll(`.project`);
const images = [].slice.call(current_project[index].querySelectorAll('.image_container img'));
const arrows = current_project[index].querySelectorAll('.arrows');
const current = current_project[index].querySelector('.current');
images[0].classList.add('active');
arrows.forEach((arrow) => {
arrow.addEventListener('click', (e) => {
let num;
images.map((image, index)=> {
if (image.classList.contains('active')){
image.classList.remove('active');
if (e.target.className == 'right'){
num = index + 1
} else {
num = index - 1
}
if (num >= images.length){
num = 0;
}
else if (num <= -1 ){
num = images.length - 1
}
console.log(num)
return num;
}
return num;
})
images[num].classList.add('active');
current.innerHTML = num + 1;
});
})
})
}).catch((error) => {
console.log(error);
})
感谢您的帮助。