将特定文本添加到随机图像阵列

时间:2017-04-27 11:14:27

标签: javascript arrays

我有一个包含6个不同图像的数组,每次加载页面时都会随机化。但是我希望在加载时为每个图像显示特定的文本。

我该怎么做?

这是我的代码:

 <script type="text/javascript">
    var random_images_array = ["../img/distraction pictures/11aabtk.jpg", "../img/distraction pictures/blue-clouds-day-fluffy-53594.jpeg", "../img/distraction pictures/cambridge-66714.jpg", "../img/distraction pictures/pandas.jpg", "../img/distraction pictures/pexels-photo-24781.jpg", "../img/distraction pictures/pexels-photo-28051.jpg"];


    function getRandomImage(imgAr, path) {
        path = path || 'img/';
        var num = Math.floor( Math.random() * imgAr.length );
        var img = imgAr[ num ];
        var imgStr = '<img src="' + path + img + '" alt = "">';
        document.write(imgStr); document.close();
    }

    </script>

2 个答案:

答案 0 :(得分:1)

您必须保留另一个数组,并从中获取值。

 var random_images_array = ["../img/distraction pictures/11aabtk.jpg", "../img/distraction pictures/blue-clouds-day-fluffy-53594.jpeg", "../img/distraction pictures/cambridge-66714.jpg", "../img/distraction pictures/pandas.jpg", "../img/distraction pictures/pexels-photo-24781.jpg", "../img/distraction pictures/pexels-photo-28051.jpg"];

 var random_texts_array = ["text1", "text6"]; //add others ..


    function getRandomImage(imgAr, path) {
        path = path || 'img/';
        var num = Math.floor( Math.random() * imgAr.length );
        var img = imgAr[ num ];
        var imgStr = '<img src="' + path + img + '" alt = "">';
        document.write(imgStr);
        document.write(random_texts_array[num]);
        document.close();
    }

答案 1 :(得分:0)

有一些方法可以去,但最简单的方法是为文本创建第二个数组......因为你正在生成随机数num ...该索引可以用于两个数组并将拉出图像及其相应的文字