What is the best way to create links between dynamically-generated HTML content with JavaScript?
For example, I have a number of thumbnail images on a homepage that should open the matching project when clicked. I've come up with this solution but I'm sure there's a better way that doesn't involve using split() to select the correct class?
The order of the thumbnails and projects will be randomised so I can't use the index of the thumbnail to open the project page with the same index.
https://codepen.io/wrgt1/pen/OJRwNQv
const thumbnail = document.querySelectorAll(".thumbnail");
const project = document.querySelectorAll(".project");
thumbnail.forEach(function (thumb) {
thumb.addEventListener("click", (e) => {
const splitClass = e.target.className.split(" ")[1];
const target = `.${splitClass}:not(.thumbnail)`;
const targetSelector = document.querySelector(target);
for (let i = 0; i < project.length; i++) {
project[i].style.visibility = "hidden";
}
targetSelector.style.visibility = "visible";
});
});
#thumbnails, #projects {
position: relative;
display: flex;
}
.thumbnail, .project {
height: 100px;
width: 100px;
margin: 10px;
}
.thumbnail {
background: #FF7400;
cursor: pointer;
}
.project {
visibility: hidden;
background: #209209;
}
<div id="thumbnails">
<div class="thumbnail project1">Thumbnail (Project 1)</div>
<div class="thumbnail project2">Thumbnail (Project 2)</div>
<div class="thumbnail project3">Thumbnail (Project 3)</div>
</div>
<div id="projects">
<div class="project project1">Project 1</div>
<div class="project project2">Project 2</div>
<div class="project project3">Project 3</div>
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…