简体   繁体   中英

How can I swap between two images on infinite clicks?

How can I swap between two images on infinite clicks (not once) using JS or jQuery

$("button").click(function(){
  $("img").attr("src","The New SRC");
});

This code works, but just once.

Try this

 var q = 0; function swapImage() { if (q == 0) { document.getElementById("image").setAttribute('src', 'https://images.unsplash.com/photo-1562102010-558d6be6268e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80'); q++; } else { document.getElementById("image").setAttribute('src', 'https://images.unsplash.com/photo-1567095740613-beef70b7e61c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80'); q--; } }
 <img id="image" src="https://images.unsplash.com/photo-1567095740613-beef70b7e61c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" onclick="swapImage();" />

If by "forever" you mean your user will always see the same image once he's changed it, you need to store that information somewhere. Here's an example where you store the image source in the browser's local storage and read that to set the src property of the image element:

 <p> <img id="my-img" src=""> </p> <button onclick="changeImage()"> Change image </button> <script> const myImg = document.getElementById("my-img") const googleLogo = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" const duckduckgoLogo = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png" const changeImage = () => { if(myImg.src === googleLogo) { myImg.src = duckduckgoLogo localStorage.setItem("img-src", duckduckgoLogo) } else { myImg.src = googleLogo localStorage.setItem("img-src", googleLogo) } } const getImageSrc = () => { const loadedSrc = localStorage.getItem("img-src") if(loadedSrc == null) { myImg.src = googleLogo } else { myImg.src = loadedSrc } } getImageSrc() </script>

Note: The code is correct but it doesn't work in the snippet because I'm reading from localStorage and this seems to be not allowed inside a snippet.

Let make this simple as possible swap the src and data-src on click.

 $('.changeSrc').on('click', function(e){ let src2= $('#img').data('src2'); $('#img').data('src2', $('#img').attr('src')); alert(src2); $('#img').attr('src', src2); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img id="img" src="./images/img1.jpg" data-src2="./images/img2.jpg"/> <button class="changeSrc">Change Picture</button>

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