繁体   English   中英

重新加载时随机化图像-JavaScript

[英]Randomize the image on reload - javascript

我有一个包含9张图像的html页面,当重新加载页面时,它们必须更改其顺序。我将图像放置为3行和3列,重新加载时应更改图像的顺序。

这是我的HTML代码

<html>
<head>
    <script type="text/javascript">
        var len = document.images.length;
        var images = document.images;
        var img = function (){
            for(var j, x, i = images.length; i; j = parseInt(Math.random() * i), x = images[--i], images[i] = images[j], images[j] = x);

            }
        window.onload = function(){
            for(var i = 0 ; i < len ; i++)
            {
                images[i].src = img[i].src;
            }
        }

    </script>
</head>

<body>

    <table>
        <tr>
            <td id="cell1"><button  value="1"><img src="1.jpg" width="42" height="42"/></button></td>
            <td id="cell2"><button  value="2"><img src="2.jpg" width="42" height="42"/></button></td>
            <td id="cell3"><button  value="3"><img src="3.jpg" width="42" height="42"/></button></td>
        </tr>
        <tr>
            <td id="cell4"><button  value="4"><img src="4.jpg"  width="42" height="42"/></button></td>
            <td id="cell5"><button  value="5"><img src="5.jpg" width="42" height="42"/></button></td>
            <td id="cell6"><button  value="6"><img src="6.jpg" width="42" height="42"/></button></td>
        </tr>
        <tr>
            <td id="cell7"><button  value="7"><img src="7.jpg" width="42" height="42"/></button></td>
            <td id="cell8"><button  value="8"><img src="8.jpg" width="42" height="42"/></button></td>
            <td id="cell9"><button  value="9"><img src="9.jpg" width="42" height="42"/></button></td>
        </tr>
    </table> 
    <!-- forms's action sends the data to a specified php page -->
    <form action="pictures.php" method="post">
        <input id="pswd" type="hidden" value="" name="pass">

    </form>
</body>
</html>

我不能随机化图像。 关于我在做什么错的任何建议:)

您应该“随机化”您的数组:

<script type="text/javascript">
    var len = document.images.length;
    var images = document.images;
    var img = function (){
        for(var j, x, i = images.length; i; j = parseInt(Math.random() * i), x = images[--i], images[i] = images[j], images[j] = x);
             }
    img = shuffle(img);//this "randomizes" the 'img' array using the function bellow
    window.onload = function(){
        for(var i = 0 ; i < len ; i++)
        {
            images[i].src = img[i].src;
        }

</script>

并将此函数粘贴到您的代码中: https : //stackoverflow.com/a/2450976/3132718

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM