用 JavaScript 和 HTML 掷硬币
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32302066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:05:20 来源:igfitidea点击:
Coin toss with JavaScript and HTML
提问by klee
I need help fixing my script. Basically, I want it to flip a coin and update a <span>
with the result, i.e. if it's heads or tails. At the moment, nothing happens when I click the button.
我需要帮助修复我的脚本。基本上,我希望它抛硬币并<span>
用结果更新 a ,即它是正面还是反面。目前,当我单击按钮时什么也没有发生。
JavaSript:
Java脚本:
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
HTML:
HTML:
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
回答by Amit
That's simply because you need to attach the event handler:
那只是因为您需要附加事件处理程序:
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
回答by SkySibe
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button" onclick="click()">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
回答by Prashant Tanwar
var prob1 = Math.floor(Math.random() * 2) +1;
var prob2 = Math.floor(Math.random() * 2) +1;
if( prob1 === prob2){
document.write('You Got TAIL');
}else{
document.write('You Got HEAD');
回答by Rhea
function flip(Throws) {
let coinArray = [];
for (var i = 0; i < Throws; i++) {
rndNo = Math.floor(Math.random() * 2 + 1);
if (rndNo === 1) {
Toss = 'H';
} else {
Toss = 'T'
} // if (rnd === 1)
coinArray.push(Toss);
}
return coinArray;
}
console.log(flip(10));
function flipHeadCoin() {
let coinArray = [];
let numHeads = 0;
do {
rndNo = Math.floor(Math.random() * 2 + 1);
// ternary operators
Toss = (rndNo === 1) ? 'H' : 'T';
numHeads += (Toss === 'H') ? 1: 0;
coinArray.push(Toss);
} while (numHeads < 6);
return coinArray;
}
console.log(flipHeadCoin());