简体   繁体   English

点击图片-打开对话框或弹出窗口

[英]Image click - Open a Dialog or Popup

I have web page which display product images. 我有一个显示产品图像的网页。 These images are coming from server (images are not specific or dynamic images ) over HTTP request in JSON format. 这些图像通过JSON格式通过HTTP请求来自服务器(图像不是特定的图像还是动态图像)。 This JSON has information about each image. 此JSON具有有关每个图像的信息。

I want to add dialog or popup box with respective image information when you click on image with Javascript ES6 Engine. 当您使用Javascript ES6 Engine单击图像时,我想添加带有相应图像信息的对话框或弹出框。 How I can pass image Information from JSON to dialog or popup when I click a specific image. 单击特定图像时,如何将图像信息从JSON传递到对话框或弹出窗口。

Let's assume you wrote 假设您写了

<img id="xyz" data-id="alpha" src="http://some.url/image.jpg" />

Then you may retrieve the id value writing 然后,您可以检索id值写作

document.getElementById("xyz").dataset.id

In your case, since you want to use the value when the image is clicked, you may use an onClick event handler, like this: 在您的情况下,由于要在单击图像时使用该值,因此可以使用onClick事件处理程序,如下所示:

<img data-id="alpha" src="http://some.url/image.jpg" onClick="someFunction();" />

and then have 然后有

someFunction = (ev) => {
    let id = ev.target.dataset.id;
    // Put here the code to open you dialog or popup
    // based on the data retrieved by using the id
}

This also works assuming you used the same image element mentioned by @Ed 假设您使用了@Ed提到的相同图像元素,这也可以工作

<img id="xyz" data-id="alpha" src="http://some.url/image.jpg" />

Then drop in the following JS to select the image by the ID: 然后放入以下JS以通过ID选择图像:

const image = document.querySelector("#xyz");

Then use the following code to "listen" for a click on the image: 然后,使用以下代码“监听”图像:

image.addEventListener("click", popup);

Then use the following code to create a popup: 然后使用以下代码创建一个弹出窗口:

function popup() {
alert("Hello! I am a popup!!");
}

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

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