Get href on maps Javascript | jquery

1

This is my code (also available at JSFiddle ):

function loadminuatura() {
  var images = $(".fileThumb").find('img').map(function() {
    return $(this).attr('src')
  });
  var array = images;
  for (var i = 0; i < images.length; i++) {
    $("#repositorio").append('<a href="' + images[i] + '"><img src="' + images[i] + '" /></a>');
  }
}

loadminuatura();
.fileThumb {
  margin: 50px;
  position: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="repositorio"></div>
<hr>
<a class="fileThumb" target="_blank" href="https://i.imgur.com/koaTwPt"><img src="https://i.imgur.com/koaTwPt.jpg"></a>
<a class="fileThumb" href="https://i.imgur.com/EDfFF8G"><img src="https://i.imgur.com/EDfFF8G.jpg"></a>
<a class="fileThumb" href="https://i.imgur.com/p2a015Z"><img src="https://i.imgur.com/p2a015Z.png"></a>
<a class="fileThumb" href="https://i.imgur.com/G8ZFdYC.png"><img src="https://i.imgur.com/G8ZFdYC.gif"></a>

It turns out that from a list of images, I go through all the "A's" with the class fileThumb and I want to get the href and the src of the image that is inside the A, and put it in the div repository that is up.

The issue is that when traveling I only get the SRC and not the HREF. And that's where I'm looking for help.

<a href="'+images[i]+'">

There I want the link from A to not the SRC of the image.

    
asked by normalito1212 18.09.2017 в 04:28
source

1 answer

0

The problem is that you are not staying with the <a> , but with the <img> , and the href is an attribute of the tag <a> . I put a solution that assumes that there is one and only one image per link (does not do many checks, but so I think it is clearer how to solve your problem)

function loadMiniatura() {
  let anchors=$("a.fileThumb");
  let anchorsHrefs=anchors.map(function() {
     return $(this).attr('href');
  });
  let imageSrcs = anchors.find('img').map(function() {
    return $(this).attr('src')
  });
  
  for (var i = 0; i < anchorsHrefs.length; i++) {
    $("#repositorio").append('<a href="' + anchorsHrefs[i] + '"><img src="' + imageSrcs[i] + '" /></a>');
  }
}

loadMiniatura();
.fileThumb {
  margin: 50px;
  position: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="repositorio"></div>
<hr>
<a class="fileThumb" target="_blank" href="https://i.imgur.com/koaTwPt"><img src="https://i.imgur.com/koaTwPt.jpg"></a>
<a class="fileThumb" href="https://i.imgur.com/EDfFF8G"><img src="https://i.imgur.com/EDfFF8G.jpg"></a>
<a class="fileThumb" href="https://i.imgur.com/p2a015Z"><img src="https://i.imgur.com/p2a015Z.png"></a>
<a class="fileThumb" href="https://i.imgur.com/G8ZFdYC.png"><img src="https://i.imgur.com/G8ZFdYC.gif"></a>
    
answered by 18.09.2017 в 10:04