简体   繁体   中英

Change image on active parent div

I have this code in which the image changes when a parent div is in an active state but it how to undo it when I click it again? How to bring back the original image? I tried putting return false at the end but it didn't work

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card egg" data-img="https://data.imgtools.co/output/tool/preview/400x400/face-extractor.png">
 <div class="card-image">
  <img src="https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3"/>
 </div>
</div>
$('.egg').click(function(){
  $(this).toggleClass("active");
  var new_src = $(this).attr('data-img');
  $(".card-image img").attr("src",new_src);
});

You can keep track of the current img src before toggling its state, overwriting the same data attribute you use to store the alternative image.

In this demo I also better dealt with the selector you used to fetch the img element, restricting its action only to the img child embedded in the clicked.egg div:

 $('.egg').click(function() { const new_src = $(this).attr('data-img'); const curr_src = $(this).find('.card-image img').attr('src'); $(this).attr('data-img', curr_src); $(this).toggleClass("active"); $(this).find('.card-image img').attr("src", new_src); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="card egg" data-img="https://data.imgtools.co/output/tool/preview/400x400/face-extractor.png"> <div class="card-image"> <img src="https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3" /> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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