抱歉,我的格式很糟糕。我希望每次单击按钮时显示一个随机报价,每次单击它时显示一个不同的报价。我需要在任何地方添加 document.write 或类似的东西吗?我确定这里和那里有一堆错误,但我只想从函数返回一个随机引用。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random quote</title>
<style>
body {
background-color: #fff;
font-family: sans-serif;
color: #28315C;
}
h1 {
text-align: center;
}
button {
border-color: #000;
background-color: #88D0FE;
color: #000;
font-size: 20px;
}
</style>
</head>
<body>
<script>
var quotes = ['this is fortune 1',
'this is fortune 2',
'this is fortune 3',
'this is fortune 4',
'this is fortune 5',
'this is fortune 6',
'this is fortune 7',
];
function newQuote(){
var randomNumber = Math.floor(math.random() * (quotes.length));
document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
</script>
</body>
<div id="quoteDisplay">
</div>
<button onclick="newQuote()">New Quote</button>
</html>
最佳答案
首先,将math
更改为Math
。此外,如果您只想设置文本内容,则可以使用 innerText
属性而不是 innerHTML
。运行下面的代码段。
<script>
var quotes = ['this is fortune 1',
'this is fortune 2',
'this is fortune 3',
'this is fortune 4',
'this is fortune 5',
'this is fortune 6',
'this is fortune 7',
];
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quoteDisplay').innerText = quotes[randomNumber];
}
</script>
<div id="quoteDisplay">
</div>
<button onclick="newQuote()">New Quote</button>
关于Javascript 函数不显示随机消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44171202/