Next and previous in jQuery array

蓝咒 提交于 2019-12-12 04:41:59

问题


So I have a jQuery array with image URLs in it:

var images = ["link1","link2","etc","etc"];

I then have this code for when the thumbnail of an image is clicked:

$('.thumbnail').click(function(){
  var link = $(this).attr('src');
  $('.large_view').prepend('<img src="'+link+'" width="450px"/>');
});

This all works fine, but I want the code to work so that when I click buttons .next and .previous, the next/previous image's URL (in the array) will replace the one currently prepended in .large_view

I assume that somehow I need to find which number in the array the clicked image is, then increase or decrease the number to that of the new image.

How should this be accomplished?


回答1:


See output below, you can use this code

  • First set index=0 and make an default image
  • on next check if not 3, increase 1 to index
  • if 3 then set back to zero
  • reverse this logic for previous

   var link = ["http://img4.wikia.nocookie.net/__cb20111201004451/internetphoto/images/8/81/Google_Image_Result_for_http-wallpaperstock.net-small-cute-kitty_wallpapers_24216_1920x1200.jpg",
            "https://lh6.ggpht.com/RIt3-kTajLWZIxunxQz9uEQp7cQ6htqFYZTcwbJXwsyKKp35BCLxKnvzswAiDfS5zQ=h310",
            "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ1NIp3cJPgEDVBQJ_jwXO27Xa-9fJqdQXuYEYa2S3NgiM8OZSf",
              "https://lh5.ggpht.com/T2acx2jKADSe1iwM6GbinPlY_1DGqF4qQAI37-ua6hwQ-DrVYDXmqRPz2HuzwrmFyQ=h310"];
 index=0;


          
 $('.large_view').prepend('<img src="'+link[index]+'" width="450px"/>');

           $('.next').click(function(){
           index = (index==link.length-1)?0:(index+1);
            
           $('.large_view img').attr('src',link[index]);
           });
    
         $('.previous').click(function(){
         index = (index==0)?(link.length-1):(index-1);
          $('.large_view img').attr('src',link[index]);
         });
div.large_view img{
width:400px;
height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="large_view">
 
  </div>

<button class="previous">previous</button>
<button class="next">next</button>


来源:https://stackoverflow.com/questions/27463232/next-and-previous-in-jquery-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!