【发布时间】:2015-11-02 15:29:09
【问题描述】:
我正在处理以下内容: http://codepen.io/anon/pen/jPJzZB
HTML:
<h1>Rock, Paper, Scissors, Lizard, Spock</h1><br>
<div id="user-choice">
<button onClick="userChoice = rock" id="rock"><i class="fa fa-hand-rock-o fa-3x"></i></button>
<button onClick="userChoice = paper" id="paper"><i class="fa fa-hand-paper-o fa-3x"></i></button>
<button onClick="userChoice = scissors" id="scissors"><i class="fa fa-hand-scissors-o fa-3x"></i></button>
<button onClick="userChoice = lizard" id="lizard"><i class="fa fa-hand-lizard-o fa-3x"></i></button>
<button onClick="userChoice = spock" id="spock"><i class="fa fa-hand-spock-o fa-3x"></i></button>
</div>
CSS:
var choices = {rock : {name: "Rock", defeats: {scissors: "crushes", lizard: "crushes"}},
paper: {name: "Paper", defeats: {rock: "covers", spock: "disproves"}},
scissors: {name: "Scissors", defeats:{paper : "cuts", lizard: "decapitates"}},
lizard: {name: "Lizard", defeats:{paper: "eats", spock: "poisons"}},
spock: {name: "Spock", defeats:{scissors : "smashes",rock : "vaporises"}}
};
var computerChoice = Math.random();
if (computerChoice <= 0.2) {
computerChoice = "rock";
} else if (computerChoice <= 0.4) {
computerChoice = "paper";
} else if (computerChoice <= 0.6) {
computerChoice = "scissors";
} else if (computerChoice <= 0.8) {
computerChoice = "lizard";
} else {
computerChoice = "spock";
}
document.write("I chose " + computerChoice + ".");
if(computerChoice == userChoice){
document.write(" It's a tie...");
}else{
userChoice = choices[userChoice];
var victory = userChoice.defeats[computerChoice] !== undefined;
computerChoice = choices[computerChoice]
if(victory) {
document.write(" You won! " + userChoice.name + " " + userChoice.defeats[computerChoice.name.toLowerCase()] + " " + computerChoice.name + "!")
}else{
document.write(" I won! " + computerChoice.name + " " + computerChoice.defeats[userChoice.name.toLowerCase()] + " " + userChoice.name + "!");
}
}
我不确定如何使用按钮 onClick 来分配变量。 javascript是对此处找到的答案的修改:Rock, Paper, Scissors, Lizard, Spock in JavaScript
【问题讨论】:
标签: javascript html onclick var