我正在创建网络游戏,其中将在屏幕上显示 3 张图像,用户必须单击与单词匹配的图像(也在屏幕上)
到目前为止,我已经制作了一个包含图像和单词的 JavaScript 数组(从数据库中填充),并设法在屏幕上的 3 个单独的 div 中从数组中打印 3 个随机图像。
目前,我真的很难同时打印出三个“属于”屏幕上随机图像之一的图像。
这是我当前的代码:-
<script>
var items = [
<?php
$con = mysql_connect("localhost","*****","******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("learning_game", $con);
$result = mysql_query("SELECT * FROM data");
$first = true;
while ($row = mysql_fetch_array($result)) {
if (!$first) {
echo ",";
}
$first = false;
echo "{name:'" . $row['word'] . "',image:'" . $row['image'] ."'}";
}
mysql_close($con);
?>
];
for (var i = 0; i < items.length; i += 1) {
}
document.write("<br /> <br /> <br />");
console.log(items);
top.items = items;
var images = new Array();
var list = document.getElementsByTagName('div')[0];
for(i = 0; i < 3; i++) {
// Choose a random item and remove it from the array
var item = items.splice(Math.floor(Math.random() * items.length), 1)[0];
// Create the image element and set its src attribute
images[i] = document.createElement('img');
images[i].src = item.image;
// Add it to your container element
}
document.getElementById("one").appendChild(images[0]);
document.getElementById("two").appendChild(images[1]);
document.getElementById("three").appendChild(images[2]);
</script>
我希望总共有 4 个 div,每个图像 1 个 div,最后一个 div 用于链接/属于其中一个图像的单词。
JavaScript 数组看起来像这样:-
var items = [
{name:'Coch',image:'upload/coch.png'}, {name:'Glas',image:'upload/glas.png'},
{name:'Melyn',image:'upload/melyn.png'},{name:'Ci',image:'upload/dog.jpg'},
{name:'Cath',image:'upload/cath.jpg'},{name:'Gwyrdd',image:'upload/gwyrdd.png'},
{name:'Un',image:'upload/un.jpg'},{name:'Dau',image:'upload/dau.jpg'},
{name:'Tri',image:'upload/tri.jpg'},{name:'Bochdew',image:'upload/bochdew.jpg'},
{name:'Piws',image:'upload/piws.png'} ];
名称是“词”。image 是文件系统中图像的链接。
任何帮助都会很棒,在此先感谢您。