javascript - 一键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 语句中。任何帮助是极大的赞赏。
解决方案
您的 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()
推荐阅读
- kdb - 使用 KDB 查询表
- javascript - 使用字符串插值时调用函数
- laravel - laravel 5.7中的自定义密码重置api
- rest - Spring boot JPA - 多个实体的自定义存储库
- elasticsearch - 从搜索查询中删除文档
- scala - SBT - 多个项目依赖于一个父级
- html - 用python填写在线表格(下拉菜单)
- c++ - 创建堆栈 VM 时出现分段错误
- javascript - 更改响应式粘性导航栏中汉堡包图标的颜色
- angular6 - Angular 6 项目中的 ng-pick-datetime 版本 7,尽量不显示时间,只显示日期并在选择日期后关闭