我有一个包含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>
我不能随机化图像。关于我做错了什么的建议:)
答案 0 :(得分:1)
你应该“随机化”你的阵列:
<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