简体   繁体   English

将 img 源值从一个 html 页面传递到另一个页面

[英]Passing img source value from one html page to another

I have two pages:我有两页:
-projects page that contain a gallery of images imported from json file -包含从 json 文件导入的图像库的项目页面
-project page that will display single image that was clicked in projects page - 将显示在项目页面中单击的单个图像的项目页面
I want to store and pass that clicked image src and import it in project page.我想存储并传递单击的图像 src 并将其导入项目页面。 I can't find a solution how to comunicate between two js files and two html files.我找不到如何在两个 js 文件和两个 html 文件之间进行通信的解决方案。
These are my codes:这些是我的代码:
projects.js项目.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项目.js

let src = localStorage.getItem(`img`);
console.log(img);

Since your application is not in a single page application you are going to redirect new page so you need to store data in localStorage or sessionStorage.由于您的应用程序不在单页应用程序中,因此您将重定向新页面,因此您需要将数据存储在 localStorage 或 sessionStorage 中。

Solution: Before redirecting the page store the data解决方案:在重定向页面之前存储数据

localStorage.setItem(`img`, imageData);

and during render the new page get the data并在渲染新页面期间获取数据

let src = localStorage.getItem(`img`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM