我试着创建一个函数来在页面每次加载时显示随机文本。代码可以工作,但如何为“parrotFact”,“lionFact”和“rabbitFact”创建一个函数呢?
由于所有功能都相同,如何将3种功能合二为一?
我分享下面的代码:
<div id="parrotFact"></div>
<div id="lionFact"></div>
<div id="rabbitFact"></div>
// JS for parrotFact
function displayRandomMessage() {
var parrotFact = [
"Parrots can talk.",
"Parrots love sunflower seeds.",
"Parrots can make your day."
];
var randomIndex = Math.floor(Math.random() * parrotFact.length);
var randomMessage = parrotFact [randomIndex];
var messageElement = document.getElementById("parrotFact");
messageElement.innerHTML = randomMessage;
}
// Call the function when the page loads
window.onload = displayRandomMessage;
// JS for lionFact
function displayRandomMessage() {
var lionFact = [
"Lion can't talk.",
"Lion is a part of cat family.",
"Lion is the King of the Jungle."
];
var randomIndex = Math.floor(Math.random() * lionFact.length);
var randomMessage = lionFact [randomIndex];
var messageElement = document.getElementById("lionFact");
messageElement.innerHTML = randomMessage;
}
// Call the function when the page loads
window.onload = displayRandomMessage;
// JS for rabbitFact
function displayRandomMessage() {
var rabbitFact = [
"Rabbit can't talk.",
"Rabbits are cute.",
"Rabbits are small."
];
var randomIndex = Math.floor(Math.random() * lionFact.length);
var randomMessage = rabbitFact [randomIndex];
var messageElement = document.getElementById("rabbitFact");
messageElement.innerHTML = randomMessage;
}
// Call the function when the page loads
window.onload = displayRandomMessage;
2条答案
按热度按时间xxslljrj1#
如果您打算为每个事实类型使用单独的HTML元素,那么您可以这样做:
将数组组合成一个对象,然后可以将希望看到的随机事实的动物类型传递给函数。
然而,如果你想一次为每种动物类型提供一个事实,那么你可以像这样迭代对象:
hvvq6cgz2#
考虑到您希望将页面上的所有内容与单个
<div>
合并考虑到您希望将页面上的所有内容与多个
<div>
合并一个二个一个一个