首页 > 解决方案 > 一键JS幻灯片序列

问题描述

我查看了许多类似的帖子,其中大多数都有一个上一个按钮,但我只需要一个按钮就可以循环返回原始照片。我尝试在这些帖子之后调整我的代码,我有点理解,但每当我调整时,我仍然会在错误之后出现错误。所以我想针对我的问题提出一个具体的问题,并希望有人可以解释/指导我哪里出错了。

<script>

var main = document.getElementById("tool");
var imgArray = ["/tools/saw.jpg","/tools/chisels.jpg","/tools/pitchfork.jpg"];
var imgIndex = 0;

function switchImg(){
    main.setAttribute("src",imgArray[imgIndex]);
    imgIndex = (imgIndex +1) % imgArray.length;
    }


</script>

<style>
img{
display: block;
margin-left: auto;
margin-right: auto;
}
.buttons{
text-align: center;
}
</style>
</head>
<body>

<img id="tool" src="/tools/saw.jpg"  height="248" width="364" alt="Saw"/>


<br/>

<div class="buttons">
<button type="button"  onClick="switchImg();"> Next </button>

错误

在此处输入图像描述

我想我可能需要一个for语句,但我不明白如何将 id=tool (在正文中)调用到 for 语句中。任何帮助是极大的赞赏。

标签: javascripthtml

解决方案


您的 html 元素尚不存在。您需要将脚本放在底部

像这样:

<style>
img{
display: block;
margin-left: auto;
margin-right: auto;
}
.buttons{
text-align: center;
}
</style>
</head>
<body>

<img id="tool" src="/tools/saw.jpg"  height="248" width="364" alt="Saw"/>


<br/>

<div class="buttons">
<button type="button"  onClick="switchImg();"> Next </button>
    <script>

var main = document.getElementById("tool");
var imgArray = ["/tools/saw.jpg","/tools/chisels.jpg","/tools/pitchfork.jpg"];
var imgIndex = 0;

function switchImg(){
    main.setAttribute("src",imgArray[imgIndex]);
    imgIndex = (imgIndex +1) % imgArray.length;
    }


</script>

由于加载 HTML,它从上到下加载,标题首先是正文,然后是正文中的所有内容。这就是为什么最佳实践是将标签放在结束标签之前的底部

你也可以使用

window.onload

或 jQuery

$( document ).ready()

推荐阅读