使用javascript的随机标语生成器';s开关
我有点小问题。我正在学习javascript,我想使用使用javascript的随机标语生成器';s开关,javascript,Javascript,我有点小问题。我正在学习javascript,我想使用switch为我的网站创建随机标语生成器 所以我创建了这个html代码 <body onload="rndqu()"> <div id="head"> <a href="index.html">Mira's place<a><br> <h2>“<span id="quote"></span>&am
switch
为我的网站创建随机标语生成器
所以我创建了这个html代码
<body onload="rndqu()">
<div id="head"> <a href="index.html">Mira's place<a><br>
<h2>“<span id="quote"></span>”</h2>
</div>
</body>
我不明白为什么它不起作用。有人能帮我吗?非常感谢。这里是jsfiddle我将使用数组而不是switch语句,以使其更灵活。例如:
var quotesList = ["I'm a great guy!", "Not even kidding.", "Just incredible."];
var randQuote = function(quotes) {
var choice = Math.floor(Math.random() * quotes.length);
return quotes[choice];
}
document.getElementById("quote").innerHTML = randQuote(quotesList);
这样,引号数组的大小可以自由更改,而无需更改任何代码
演示:我将使用数组而不是switch语句来实现这一点,以使其更加灵活。例如:
var quotesList = ["I'm a great guy!", "Not even kidding.", "Just incredible."];
var randQuote = function(quotes) {
var choice = Math.floor(Math.random() * quotes.length);
return quotes[choice];
}
document.getElementById("quote").innerHTML = randQuote(quotesList);
这样,引号数组的大小可以自由更改,而无需更改任何代码
演示:您将部分代码留在了
rndqu()函数之外。
我用叉子把你的小提琴改过来了:
以下是更正后的JS代码:
var qu;
var slogan;
function rndqu(n)
{
var random = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
qu = random(1, 3);
switch(qu){
case 1:
slogan = "Here is the 1";
break;
case 2:
slogan = "Here is the 2";
break;
case 3:
slogan = "Woah";
break;
default:
slogan = "Really?";
}
document.getElementById("quote").innerHTML = slogan;
}
您将部分代码留在rndqu()
函数之外。
我用叉子把你的小提琴改过来了:
以下是更正后的JS代码:
var qu;
var slogan;
function rndqu(n)
{
var random = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
qu = random(1, 3);
switch(qu){
case 1:
slogan = "Here is the 1";
break;
case 2:
slogan = "Here is the 2";
break;
case 3:
slogan = "Woah";
break;
default:
slogan = "Really?";
}
document.getElementById("quote").innerHTML = slogan;
}
固定在这里
您的代码过于复杂,请注意,在JSFIDLE中不要添加body onload=“()”
函数。Jsfiddle为您做这件事
如果您想在真实网页上执行onbodyload
,请将代码包装在以下内容中:
window.onload = (function(){
//your code goes here
})
或者将脚本包含在html文件的底部
只要有可能,最好的做法就是避免在html中使用内联javascript。此处已修复
您的代码过于复杂,请注意,在JSFIDLE中不要添加body onload=“()”
函数。Jsfiddle为您做这件事
如果您想在真实网页上执行onbodyload
,请将代码包装在以下内容中:
window.onload = (function(){
//your code goes here
})
或者将脚本包含在html文件的底部
只要可能,最佳实践就是避免在html中使用内联javascript