首页 > 解决方案 > 如何使用 JavaScript 在动态内容之间创建链接?

问题描述

使用 JavaScript 在动态生成的 HTML 内容之间创建链接的最佳方法是什么?

例如,我在主页上有许多缩略图,单击时应打开匹配的项目。我想出了这个解决方案,但我确信有更好的方法不涉及使用 split() 来选择正确的类?

缩略图和项目的顺序将是随机的,因此我无法使用缩略图的索引打开具有相同索引的项目页面。

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>

我真的很感激任何想法!

标签: javascripthtmlcss

解决方案


看不出你的代码有什么问题,我也以不同的方式尝试过

希望你也看看

const thumbnail = document.querySelectorAll(".thumbnail");
const project = document.querySelectorAll(".project");

thumbnail.forEach(function (thumb) {
    thumb.addEventListener("click", (e) => {        
        const target = e.target.classList[1];
        project.forEach(function (pro) {
            pro.style.visibility = "hidden";
            if( pro.classList.contains(target)){
              pro.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>


推荐阅读