通过onclick事件将一张图片更改为6张图片

Getting a picture to change through 6 pictures via an onclick event

本文关键字:6张 一张 事件 onclick 通过      更新时间:2023-09-26

在继续之前,我必须解释我只做了一周半的代码。无论如何,我正在尝试建立我的第一个网页,我不知道或找不到一种方法,在每次按下按钮的6张图片之间切换。

到目前为止,这是我的html和javascript代码。

这是我的html中唯一相关的部分。

<button id="but" onclick="modify_qty(1); picChange();" />Pushy Pushy</button>
<img id="picture" src="pic1.jpg" height="500" width="1365">

这是JavaScript,我正在使用jquery和

function picChange() {
document.getElementById("picture").src="pic2.jpg";
if (document.getElementById("picture").src="pic2.jpg") {
    document.getElementById("picture").src="pic3.jpg";  
    }
}

我认为可能有效的代码只是跳过pic2.jpg,所以help会非常有用。

您可以将图像的url存储在一个数组中。然后,您可以在单击按钮时设置图像标记的来源。您可以使用计数器来"记住"显示的图像。在下面的示例中,当显示最后一个图像时,我进行计数器重置(counter = 0)。

JSFIDDLE演示

var images= [
"http://26.media.tumblr.com/tumblr_lo7izpkVSJ1qcdfs3o1_250.jpg",
"http://28.media.tumblr.com/tumblr_lnqquri96C1qcdfs3o1_250.jpg",
"http://28.media.tumblr.com/tumblr_lmddmmNCAl1qcdfs3o1_250.jpg",
"http://28.media.tumblr.com/tumblr_lmddmky4SR1qcdfs3o1_250.jpg",
"http://24.media.tumblr.com/tumblr_lmddmi79Ek1qcdfs3o1_250.jpg",
"http://28.media.tumblr.com/tumblr_lle7rf5SYi1qcdfs3o1_250.jpg"
]
var img = $('#imgcycle');
var counter= 0;
$('button').on('click', function(){
    if(counter == images.length){
        counter = 0;
    }
    console.log(counter);
    img.attr('src', images[counter]);
    counter++;
})

如果图像都是相同的名称,末尾有不同的数字,那么你可以用jquery做这样的事情:

i = 1;
$('#but').click(function() {
  $('#picture').attr('src', 'pic' + i + '.jpg');
  console.log($('#picture').attr('src'));
  i++;
  if (i == 7) {
    i = 0;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="but">Pushy Pushy</button>
<img id="picture" src="pic1.jpg">