Home > Enterprise >  Can't target each image element with a different api link
Can't target each image element with a different api link

Time:12-31

I am trying to get different images to show up for each image element I have. The problem is mostly in my render function. Right now only one image shows up for all of the image elements in my html.

HTML

  <table >
    <tr>
      <td><img  src=""></td>
      <td><img  src=""></td>
      <td><img  src=""></td>
      <td><img  src=""></td>
    </tr>
    <tr>
      <td><img  src=""></td>
      <td><img  src=""></td>
      <td><img  src=""><td>
      <td><img  src=""><td>
    </tr>
  </table>

JavaScript

function getGiphy(evt) {
  evt.preventDefault();

  const userInput = $input.val()



  if(!userInput) return

  $.ajax(URL   userInput).then(function(data) {
    render(data)
  
  },  function(error) {
    return (error, 'something went wrong')
  })
}

function render(gifData) {
  // function getRandomIdx(min, max) {
  //   return Math.floor(Math.random() * (max - min)   min)
  // }
  // randIdx = getRandomIdx(0, 20)


  // $(".row1").each(gifData, function(idx, element){

  // })

  for (x = 0; x < 9; x  ) {
    let gifId = x
    $('.gif').each(function(){
      $(this).attr("src", gifData.data[gifId].images.original.url)})
  }
}

CodePudding user response:

function getGiphy() {
let links =['http://test1', 'http://test2', 'http://test3', 'http://test4', 'http://test5', 'http://test6', 'http://test7', 'http://test8']

render(links)
}


function render(gifData) {
console.log(gifData)
  $('.gif').each(function(index){
      $(this).attr("alt", index);
      $(this).attr("src",
           gifData[index])
  })
}

getGiphy();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table >
    <tr>
      <td><img  src="" alt=""></td>
      <td><img  src="" alt=""></td>
      <td><img  src="" alt=""></td>
      <td><img  src="" alt=""></td>
    </tr>
    <tr>
      <td><img  src="" alt=""></td>
      <td><img  src="" alt=""></td>
      <td><img  src="" alt=""></td>
      <td><img  src="" alt=""></td>
    </tr>
  </table>

I can't call your ajax - that's why I reworked the code to show you how to do it

  • Related