我正在尝试创建一个网站,从数组中选择随机内容来制作句子。它应该从objectArray
中选择一个随机项,然后通过div
document.getElementById()
代码
<script>
var objectArray = ["computer", "iphone", "duck", "candle", "oven", "sofa", "curtain", "blanket", "star", "piano", "turtle", "fluffiness", "door", "pillow", "funny face", "lamp", "healthy heart", "rainbow", "lamp", "clock", "coat", "just luck", "stop sign", "window"];
var randObject = objectArray[Math.floor(Math.random() * objectArray.length)];
document.getElementById("Objecto").innerHTML = "randObject";
</script>
<center>
<div id="Objecto"></div>
</center>
答案 0 :(得分:1)
您将元素的innerHTML
设置为字符串文字"randObject"
,而不是变量randObject
的内容。请改用:
document.getElementById("Objecto").innerHTML = randObject;
这是一个完整的代码段:
var objectArray = ["computer", "iphone", "duck", "candle", "oven", "sofa", "curtain", "blanket", "star", "piano", "turtle", "fluffiness", "door", "pillow", "funny face", "lamp", "healthy heart", "rainbow", "lamp", "clock", "coat", "just luck", "stop sign", "window"];
var randObject = objectArray[Math.floor(Math.random() * objectArray.length)];
document.getElementById("Objecto").innerHTML = randObject;
<center>
<div id="Objecto"></div>
</center>