我正在使用以下内容: 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
答案 0 :(得分:1)
这很简单!有两种选择:
在HTML中使用内联JavaScript。
使用JavaScript DOM API完成此任务。
选项#1:
<button onclick="alert('Yeah!!, I was clicked')">Click me!</button>
&#13;
选项#2:
document.getElementById('btn').onclick = function(){
alert('Yeah!!!, I was clicked');
}
&#13;
<button id="btn">Click me!</button>
&#13;
请注意,变量赋值与此非常相似,唯一的区别是您应该通过赋值语句替换该alert语句。