简体   繁体   English

如何获取我在此javascript函数中单击的图像索引?

[英]How can I get the indexof image I clicked in this javascript function?

There is a recently viewed list that when I click one image the image will appear in the list. 最近查看的列表是,当我单击一个图像时,图像将出现在列表中。
But for now I can not get the image I want and I just use the first image to appear in list when I click an image, like in the code ${photos[0].file} . 但是现在我无法获得我想要的图像,当我点击图像时,我只是使用第一个图像出现在列表中,就像在代码${photos[0].file}
So How can I get the image I clicked to recent viewed list? 那么如何才能获得我点击最近查看过的列表的图像?

function display(photos) {

  let htmlStr = "";
  for (let i = 0; i < photos.length; i++) {
    htmlStr += `<figure data-full="${photos[i].full}" title="${photos[i].title}" file="${photos[i].file}"><img src = "${photos[i].file}"  alt="City view" height="200" width="200"><figcaption>${photos[i].title}</figcaption></figure>`;

  }
  $("#container").html(htmlStr);

  let htStr = "";
  $('figure').each(function(index) {

    $(this).click(function() {
      htStr += `<figure id='recentphoto' data-full="${photos.full}" title="${photos.title}"><img src = "${photos[0].file}" alt="City view" height="140" width="140"><figcaption >${photos[0].title}</figcaption></figure>`;
      $("#recent").html(htStr);

    });

  });

 $(document).ready(function() { var photos = [ { full: 'full1', title: 'title1', file: 'file1' }, { full: 'full2', title: 'title2', file: 'file2' }, ]; let htmlStr = ""; for (let i = 0; i<photos.length; i++) { htmlStr += `<figure data-full="${photos[i].full}" data-title="${photos[i].title}" data-file="${photos[i].file}" title="${photos[i].title}" file="${photos[i].file}"><img src = "${photos[i].file}" alt="City view" height="200" width="200"><figcaption>${photos[i].title}</figcaption></figure>`; } $("#container").html(htmlStr); let htStr = ""; $('figure').click(function(e) { var el = $(this).data(); htStr += `<figure id='recentphoto' data-full="${el['full']}" title="${el['title']}"><img src = "${el['file']}" alt="City view" height="140" width="140"><figcaption >${el['title']}</figcaption></figure>`; $("#recent").html(htStr); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"></div> <div id="recent"></div> 

You can get help of data attributes of jQuery. 您可以获得jQuery数据属性的帮助。

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

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