按顺序获取数组中的项目,然后重复?

时间:2018-10-05 06:55:33

标签: javascript html

     <img src="link" id="hof" </div> 
    <span id="myspan">Compliment: </span>

    <script type="text/javascript">

        function change() {
        // ---------- Caption and images !! -----------//
        var things = ["Slide01", "Slide04", "Slide05", "Slide06"];
        var captions = ["Very nice", "Awesome", "Cool", "Best"];
        // ^^^^^^^^^^ Captions and Images !! ^^^^^^^^^^ //         

        var image = document.getElementById('hof');
        var thing = things[];
        image.src = "link" + thing + ".jpg"; // change the image   

        span = document.getElementById("myspan");
        span.innerText= "Compliment: " + captions[]; //change caption
        }
        setInterval('change()', 4000);

        </script> 

所以我是Java语言的新手,我正在尝试制作带字幕的幻灯片,但是我需要数组中的值才能按顺序显示,例如(slide01> slide02> slide03),然后在到达最后一个值时从头开始重复。

2 个答案:

答案 0 :(得分:9)

要回答您的实际问题:您将使用在外部 index定义的change变量。从0开始,然后(在渲染幻灯片之后)将其递增,直到到达things.length为止。最后一部分有一个窍门:

index = (index + 1) % things.length;

其他说明:

  1. 不要使用并行数组,而要使用对象数组。

    var slides = [
        {name: "Slide01", caption: "Very Nice"},
        // ...
    ];
    

    然后

    var slide = slides[index];
    image.src = "link" + slide.name + ".jpg";
    span.innerText = "Compliment: " + slide.caption + ".jpg";
    
  2. change之外定义该数组,无需每次调用​​change时都重新创建它。

  3. 不要将字符串传递到setIntervalsetTimeout中;传入函数代替:

    setInterval(change, 4000);
    
  4. 考虑将所有代码包装在作用域函数中,因此index,幻灯片数组和change函数不是全局变量:

    (function() {
        // ...your code here...
    })();
    

答案 1 :(得分:0)

<body onload="imgcarousel()">
   <img src="" id="hof">
   <p id="caption"></p>
   <button onclick="imgcarousel()">Next</button>
</body>

<script>
    var count = 0;
    var things = ['Slide01', 'Slide04', 'Slide05', 'Slide06'] ;
    var captions = ['Very Nice','Awesome','Cool','Best'];
    function imgcarousel()
    {            
        count++;
        var img = document.getElementById("hof");
        var caption = document.getElementById("caption");
        if(count >= things.length)
            {
                count = 0;
            }            
        img.src = things[count]+".png";
        caption.innerHTML = "Compliments: " +captions[count];

    }
</script>