gpt4 book ai didi

javascript - 通过单击按钮更改数组中的图片

转载 作者:行者123 更新时间:2023-12-03 07:13:16 24 4
gpt4 key购买 nike

我有一个关于数组中图片的问题。我可以通过单击更改图片,但只能更改一次。这是我的代码,带有一些示例图片。网上有很多教程,但对我来说可能太复杂,所以我创建了一个简单的东西。

<html>
<head>
<script type="text/javascript">
//here I am creating my array
var myPicture = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
]

// this should be the function and I think here is the error
function nextPic() {
myPicture[1] = document.images;
}
</script>
</head>
<body>
<img src="http://www.java2s.com/style/download.png" width="107" height="98" />
<form>
<input type="button" onclick="nextPic()" value="Change image">
</form>
</body>
</html>

简单的问题是,我必须在代码中更改什么才能一键显示第二个、第三个、x 图片。或者有一个简单的 jQuery 函数吗?

最佳答案

这是一个工作示例:http://jsbin.com/dubuhizucu/edit?html,console,output

有几件事..

1) 您需要一个变量来跟踪您在 pictures 数组中的位置。

2) 单击时,增加步骤 1 中的变量。然后,检查它是否大于图片数组的长度。如果是,那么我们需要将其重置回 0。

3) 只需将图像上的 src 属性设置为图片数组中的 URL,将索引设置为 counter 的值即可!

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="http://www.java2s.com/style/download.png" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />



<script>
var target = document.getElementById('target');
var counter = 0;
var myPictures = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
];

function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
</script>
</body>
</html>

关于javascript - 通过单击按钮更改数组中的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36535549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com