我希望代码获取用户在输入字段中输入的值并将其传递给变量userChoice。我不知道为什么这段代码不起作用,唯一的学习方法就是问你们。
HTML:
<h3> Choose your destiny !</h3>
<form>
<input type="text" id="form" />
<input type="button" id="button" value="Click Me!" onclick="clickMe();" />
</form>
JavaScript的:
var computerChoice = Math.random();
var userChoice = "";
function clickMe() {
document.getElementById("form").value === userChoice;
}
if (computerChoice < 0.33) {
computerChoice = "rock";
};
if (computerChoice < 0.66) {
computerChoice = "paper";
};
if (computerChoice < 1) {
computerChoice = "scissors";
};
if (userChoice === "rock" && computerChoice === "rock") {
alert("It's a tie!");
} else if (userChoice === "rock" && computerChoice === "paper") {
alert("Computer Wins!");
} else if (userChoice === "rock" && computerChoice === "scissors") {
alert("You WIN!");
};
if (userChoice === "paper" && computerChoice === "rock") {
alert("You WIN!");
} else if (userChoice === "paper" && computerChoice === "paper") {
alert("It's a TIE!");
} else if (userChoice === "paper" && computerChoice === "scissors") {
alert("Computer Wins!");
};
if (userChoice === "scissors" && computerChoice === "rock") {
alert("Computer Wins!");
} else if (userChoice === "scissors" && computerChoice === "paper") {
alert("You WIN!");
} else if (userChoice === "scissors" && computerChoice === "scissors") {
alert("It's a TIE!");
};
答案 0 :(得分:2)
你的功能clickMe
不能像你期望的那样工作:
function clickMe() {
userChoice = document.getElementById("form").value;
// ... rest of your code goes inside clickMe
}
要为变量指定值,您需要一个=
答案 1 :(得分:0)
这是简单的方法
<div id="Result"></div>
<div id="sellection">
<a href="javascript:;" onClick="result(0)">Rock</a>
<a href="javascript:;" onClick="result(1)">Paper</a>
<a href="javascript:;" onClick="result(2)">Scissors</a>
</div>
,脚本是:
function result(users){
var choices = ["Rock","Paper","Scissors"];
var succesResult = "You Loose :(";
var machines = Math.floor((Math.random() * 3));
var dif = users-machines;
if(dif>0&&dif!=2||dif==-2){
succesResult = "You Win :)";
}else if(dif==0){
succesResult = "You Draw";
}
var resultText = "You Selected "+choices[users]+", Computer Selected "+choices[machines]+" and "+succesResult;
document.getElementById("Result").innerHTML = resultText;
}