Home > Back-end >  Jquery how to replace img to another img by click
Jquery how to replace img to another img by click

Time:10-11

I have a question.

I have some code in html page

$(document).ready(function() {
  $("#img-1").click(function() {
    var imgsrc = $(this).attr('src');
    $(".click-img").attr('src', imgsrc);
  });
});

$(document).ready(function() {
  $("#img-2").click(function() {
    var imgsrc = $(this).attr('src');
    $(".click-img").attr('src', imgsrc);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div>
  <tr>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/mults_dobicha_ognya.gif" id="img-1"></td>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/animaciya.gif" id="img-2"></td>
  </tr>
</div>

<div>
  <tr>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/risunki_svecha.gif" class="click-img" id="select-1"></td>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/risunki_svecha.gif" class="click-img" id="select-2"></td>
  </tr>
</div>

And how can I change img by replace. For example: i click to image with id="img-1" then click image with id="select-1". And image id="img-1" replaced by id="select-1" ?

My Jquery is not working and i can't understand how solve this problem. So do you have some better solution?

CodePudding user response:

I don't know if this is exactly what you were looking for but it can always give you an idea

$(document).ready(function() {
    var srcCopy = '';
  
  $(".defaultImg").click(function() {
    srcCopy = $(this).attr('src');
  });
  
   $(".click-img").click(function() {
      if( srcCopy ){
        $(this).attr('src', srcCopy);
        srcCopy = '';
      }
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div>
  <tr>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/mults_dobicha_ognya.gif" id="img-1"class="defaultImg" ></td>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/animaciya.gif" id="img-2" class="defaultImg" ></td>
  </tr>
</div>

<div>
  <tr>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/risunki_svecha.gif" class="click-img" id="select-1"></td>
    <td><img src="https://avatarko.ru/img/avatarka/100na100/risunki_svecha.gif" class="click-img" id="select-2"></td>
  </tr>
</div>

  • Related