上一个函数不起作用

Previous function not working

本文关键字:不起作用 函数 上一个      更新时间:2023-09-26

我正在制作一个javascript幻灯片,但我不知道如何为每张图片添加标题,上一个按钮工作不正常(点击两次或多次后没有显示任何图片),我如何才能转到幻灯片的第一张和最后一张图片?

var index=4;
var titles=[1,2,3,4,5];

// LIST OF CAPTİONS
caption[0] = "Caption for the first image";
caption[1] = "Caption for the second image";
caption[2] = "Caption for the third image";
caption[3] = "Caption for the first image";
caption[4] = "Caption for the second image";
caption[5] = "Caption for the third image";
function NextSlide()
{
    if (index >= 5){index=0}
    var img = document.getElementById("img1");
    var slideName="images/img" + titles[index++] + ".jpg";
    img.src=slideName;
}
function PrevSlide()
{
    if (index >= 5){index=0}
    var img = document.getElementById("img1");
    var slideName="images/img" + titles[index--] + ".jpg"; img.src=slideName;
}
function last()
{
    index = 1;
}

下面的代码给出了如何实现first()和last()方法以及更改标题的示例。您还没有提供任何HTML,因此可能需要对其进行测试/调整以适应您所拥有的内容(例如,您需要添加spanp标签来包含ID为caption1的标题)

var index = 3;   // index for forth image as it's zero based
// List of captions
var captions  = ["Caption for the first image",
                 "Caption for the second image",
                 "Caption for the third image",
                 "Caption for the forth image",
                 "Caption for the fifth image",
                 "Caption for the sixth image"];
var slideShowImg = document.getElementById("img1");
var slideShowCaption = document.getElementById("caption1");
// Show current image
function showCurrentImage(){
    var slideName = "images/img" + (index + 1) + ".jpg";
    slideShowImg.src = slideName;
    slideShowCaption.innerText = captions[index];
}
// Move to next slide
function nextSlide()
{
    index++;
    if (index >= captions.length){ index = 0; }
    showCurrentImage();
}
// Move to previous slide
function prevSlide()
{
    index--;
    if (index < 0){ index = captions.length - 1; }
    showCurrentImage();
}
// Move to last slide
function last()
{
    index = captions.length - 1;
    showCurrentImage();
}
// Move to first slide
function first()
{
    index = 0;
    showCurrentImage();
}

HTML可能类似于。。。

<div class="slide-show">
  <img src="#" id="img1" alt="" />
  <span id="caption1">Caption</span>
</div>

注:

  • 您的变量titles只是在索引中添加了一个,所以我删除了它并添加了内联。

  • 我把标题移到了一行,而不是一个接一个地定义。

  • 将getElementById("img1")移出该方法,因为它只是在每次时重复自己

  • 创建showCurrentImage()来更改页面,所有其他方法只需更改索引,然后调用这个

  • 修复了prevSlide()中第一个项目的测试(看起来像是从nextSlide(复制的)