シャッフル関数で開始します(配列をシャッフルします)。できます。 次に、ページに表示される画像のランダムな順序を決定する2つのグローバル変数を定義します。 picOrderは、0からpicCountまでの単純な配列で、picCountはAjax onloadによって決定されます。 picCountが取得されていますが、picOrder配列が設定されていません!私が手動で "arrangePics();"を実行するとコンソール上で動作します。配列picOrderを塗りつぶしてシャッフルします。しかし、両方の関数への呼び出しを ""内部に置くか、または "doStuff()"関数をそこに置くことによっては機能しません。onLoadをAjaxで実行するには2つの関数が必要 - 1つしか動作しません。
Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
while (s.length) this.push(s.pop());
return this;
}
var picOrder = new Array();
var picCount;
function getPicCount() {
// picCount = array(10);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
picCount = xmlhttp.responseText;
}
}
xmlhttp.open("GET","/example.com/images.php?count=hello",true);
xmlhttp.send();
//picCount.shuffle;
}
function arrangePics() {
for(var i = 0;i<picCount;i++) {
picOrder[i] = i;
}
picOrder.shuffle();
//alert(picOrder);
}
HTML
<body onLoad="getPicCount();arrangePics();">
または
<body onLoad="doStuff();">