我的幻灯片网站仅在单击按钮两次以运行 JS 时才有效

My slideshow website only works when clicking the button twice to run the JS?

本文关键字:两次 运行 JS 有效 网站 幻灯片 单击 按钮 我的      更新时间:2023-09-26

我想通过单击来制作幻灯片,但只需单击两次即可。

这是我的代码:

变量指数=0;var titles=[1,2,3,4,5,6,7,8,9,10];

function moveToNextSlide()
{
if (index >= 10){index=0}
var img = document.getElementById("img1");
var slideName="images/img" + titles[index++] + ".jpg";
img.src=slideName;
}

}

HTML 代码是:

 <input type="button" onClick="javascript:moveToNextSlide()" value="Next">


<input type="button" onClick="javascript:moveToLastSlide()" value="Last">


<input type="button" onClick="javascript:moveToRandom()" value="Random"> </p>

<script>
moveToNextSlide();
moveToPreviousSlide();
</script>

你应该做var slideName="images/img" + titles[++index] + ".jpg";

你需要这样做

var slideName="images/img" + titles[++index] + ".jpg";

始终声明变量,这是一个很好的编程实践