的版本的jsfiddle没有工作,所以我添加了一个codepen代替 Working Codepen如何使用与jQuery或JavaScript
按钮刷新可变我是相当新的JavaScript和jQuery的,所以我道歉如果我的措辞不太对,或者答案非常明显,我就来这里学习:)所以我制作了一个摇滚纸剪刀游戏,除了我的“新游戏”按钮,一切都很棒。我无法弄清楚如何刷新变量'computerChoice'。我已经能够设置它以便页面刷新,但这不是我想要实现的。我需要它,当你点击'新游戏'时,变量'computerChoice'将根据随机数选择一个新选项,就像刷新页面一样。我已经尝试将它设置为空,当你点击“新游戏”,但是当你去玩游戏时,它只是返回数字。
HTML:
<h1>Rock Paper Scissors</h1>
<h2>Pick your weapon!</h2>
<p><button id="refresh">New Game</button></p>
<button onClick='choose("rock")' class="choices">Rock</button>
<button onClick='choose("paper")' class="choices">Paper</button>
<button onClick='choose("scissors")' class="choices">Scissors</button>
<p><button onClick='compare(user, computerChoice)' class="compares">1...2...3...</button></p>
<p><b id="you">...</b> Vs.
<b id="computer">...</b></p>
<p><b id="results"></b></p>
的JavaScript:
//user choices
var user;
var choose = function(choice) {
user = choice;
//document.getElementById("you").innerHTML = user;
}
//computer choices
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
}
else if (computerChoice < 0.67) {
computerChoice = "paper";
}
else {
computerChoice = "scissors";
}
//compare user choice to computer choice
function compare(choice1, choice2) {
if (choice1 === choice2) {
document.getElementById('results').innerHTML = "How boring, you tied.";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
document.getElementById('results').innerHTML = "They'll feel that in the morning.";
} else {
document.getElementById('results').innerHTML = "Can you breathe? I think not.";
}
}
else if (choice1 === "scissors") {
if (choice2 === "paper") {
document.getElementById('results').innerHTML = "Snippitysnip, you sliced them in two.";
} else {
document.getElementById('results').innerHTML = "Ouch, looking a little blunt.";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
document.getElementById('results').innerHTML = "You smothered them, eesh!"
} else {
document.getElementById('results').innerHTML = "You're looking a bit like a banana split."
}
}
else {
document.getElementById('results').innerHTML = "Something's not quite right...what did you do?!"
}
}
// refresh, clear and display computer choices and results. Disable, enable buttons.
function disableButtons() {
$('button.choices').attr('disabled', true);
}
function enableButtons() {
$('button.choices').attr('disabled', false);
}
$('.choices').click(function() {
$('#you').html(user); // this works on codepen but not on jsfiddle? D:
$('#computer').html('...');
disableButtons();
});
$('#refresh').click(function() {
$('#results').html('');
$('#you, #computer').html('...');
enableButtons();
refreshComputer();
});
$('.compares').click(function() {
$('#computer').html(computerChoice);
});
的版本的jsfiddle没有工作,所以我添加了一个codepen代替 Working Codepen
'refreshComputer'定义在哪里? –
检查您的控制台。遍地都有错误,大部分或全部都与变量或函数范围有关。 –
对于这样一个更复杂的问题,最好把它放到[JSFiddle](https://jsfiddle.net/)或[CodePen](https://codepen.io/)中,让它工作在那里,那么找出一个有用的解决方案会变得更容易。 – samanime