我有两个页面:
-项目页面,包含从json文件导入的图像库
-项目页面,将显示在项目页面中单击的单个图像
我想存储并通过单击图像src并将其导入项目页面。我找不到一个解决方案,如何在两个js文件和两个html文件之间进行通信。
我的代码如下:
projects.js
const projectsGallery = document.querySelector('.projects__wrapper');
axios
.get('../data.json')
.then(async response => await response.data)
.then(data => {
const displayProjects = function (project) {
projectsGallery.innerHTML = ``;
project.forEach(project => {
const card = `
<div class="card"> <form action="submit" method=POST>
<img src=${project.src} id="myImg" class="img__project gallery-img" alt=${project.alt}></img>
<h1 class="hvr-grow">${project.projectName}</h1>
<div class="card__btn-wrapper">
<a class="card__btn hvr-sweep-to-left" href=${project.code}>
See Code
</a>
<a class="card__btn hvr-sweep-to-right" href=${project.live}>
Live
</a>
</form>
</div>
</div>
`;
projectsGallery.insertAdjacentHTML(`beforeend`, card);
});
modalFunc();
};
displayProjects(data.projects);
images.forEach(image => {
image.addEventListener(`click`, function () {
const images = document.querySelectorAll('.gallery-img');
let img = image.src;
window.document.location = `/pages/project.html`;
});
});
});
project.js
let src = localStorage.getItem(`img`);
console.log(img);
由于您的应用程序不是单页应用程序,您将重定向新页面,因此您需要将数据存储在localStorage或sessionStorage中。
解决方案:在重定向页面之前存储数据
localStorage.setItem(`img`, imageData);
,在渲染新页面时获取数据
let src = localStorage.getItem(`img`);