Caption Array Gallery Foto tidak berfungsi

Kenapa ya caption array skrip di bawah ini tidak berfungsi? Pada halaman pertama, caption-nya 1, pada halaman kedua, caption-nya , (koma), pada halaman ke 3, caption-nya 2, pada halaman keempat, caption-nya ,(koma), dan seterusnya ? Apakah ada solusi ? Seharusnya caption-nya 1, 2, 3, 4, 5, 6

<html>
<head>
    <title>Photo Gallery</title>
    <style>
        .image{
            width=300px;
            height=300px;
        }
    </style>
    <script>

    var num;
    var name = ["", "1", "2", "3", "4", "5", "6"];

        function change(n){
            num = n;
            var path = "img/" + n + '.png';
            document.getElementById('text').innerHTML = name[n];
            document.getElementsByTagName("img")[0].src=path;
            return false;
        }

        function next(){
            if(num >=6){
                num = 1;
            }else{
            num = num + 1;
            }

            change(num);
        }

        function prev(){
            if(num <=1){
                num = 6;
            }else{
            num = num - 1;
            }

            change(num);
        }


    </script>
</head>
<body onload="change(1)">
     <a href="#" onclick="prev()">Prev</a>
     <a href="#" onclick="change(1)">1</a>
     <a href="#" onclick="change(2)">2</a>
     <a href="#" onclick="change(3)">3</a>
     <a href="#" onclick="change(4)">4</a>
     <a href="#" onclick="change(5)">5</a>
     <a href="#" onclick="change(6)">6</a>
     <a href="#" onclick="next()">Next</a>

     <br>
     <br>
     <img src="" class="image" alt="">
     <br>
     <p id="text"></p>

</body>
</html>
avatar billyhalim
@billyhalim

2 Kontribusi 0 Poin

Diperbarui 8 tahun yang lalu

3 Jawaban:

hmm.. kelihatannya udah bener, kalo gambarnya udah bener ya?

avatar hilmanski
@hilmanski

2670 Kontribusi 2132 Poin

Dipost 8 tahun yang lalu

Jawaban Terpilih

Nah bro, ada sedikit ilmu disini, kita tidak bole mendeklarasikan variable dengan "name" karena "name" itu berasal dari "windows.name". "Window.name" ini sendiri bs konvert array ke string.

Dari stackoverflow.com :

Since you define name in the global scope it overwrites the window.name property which is string, as a result your array is converted into a string ,1,2,3,4,5,6 instead of array. Use a different variable name like names to avoid that. Also the best would be to use event handlers and separate your html from the javascript and you will be able to use namespaces that will not pollute the window object with global variables.

https://developer.mozilla.org/en-US/docs/Web/API/Window/name

avatar billyhalim
@billyhalim

2 Kontribusi 0 Poin

Dipost 8 tahun yang lalu

wihh menarik gan, makasih banyak udah mau dishare

avatar hilmanski
@hilmanski

2670 Kontribusi 2132 Poin

Dipost 8 tahun yang lalu

Login untuk ikut Jawaban