【发布时间】:2021-10-10 17:11:31
【问题描述】:
我一直在尝试将一些 HTML/CSS 功能应用到您在下面看到的简单 JS 代码中,其中包括基于两个数组返回一个随机句子。
我想创建一个简单的 onclick 按钮来显示生成的句子,但我仍然无法让它工作。你有什么想法或线索吗?我已经设法用变量/文本完成了它,但是在访问函数时我遇到了一些问题,这当然是程序的重点。
提前感谢大家的帮助。
JS:
const personArr = ["Father Burgundy", "Constable Grey"];
const locationArr = ["the sauna", "the larder"];
const selectArr = (array) => {
return(array[Math.floor(Math.random()*array.length)]);
}
const createMessage = () => {
const message = "It was " + selectArr(personArr) + " in " + selectArr(locationArr)"!";
return message;
};
const init = () => {
const message = createMessage();
console.log(message);
};
init();
----------------------------
function demo() {
document.getElementById("output").innerHTML = init();
}
HTML:
<button id="btn" onclick="demo()">Click here!</button>
<p id="output"></p>
【问题讨论】:
-
您的
init()函数应该返回“输出”元素的实际内容。现在它什么也不返回。您是否像在createMessage()中那样尝试过return message;?
标签: javascript html button onclick