我正在使用javascript / JQuery运行这个html文档,在回答提示后,没有任何反应。似乎追加功能不起作用。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>
Rock Paper Scissors
</title>
<script>
var userChoice = prompt("Do you choose rock, paper, scissors lizard or spock?");
userChoice = userChoice.toLowerCase();
var computerChoice = function(){
var choices = ["rock", "paper", "scissors", "lizard", "spock"];
var random = Math.random();
var loop = true;
while (loop){
i = 0.2;
j = 0;
if (random <= i){
var choices = choices[j]
var loop = false;
}
else {
i = i +0.2;
j ++;
}
}
return choices;
};
$(document).ready(function(){$("body").append(userChoice);});
$(document).ready(function(){$("body").append(computerChoice());});
</script>
</head>
<body>
</body>
</html>
答案 0 :(得分:3)
这有点不对劲。
我已经为你清理了一下 - jsfiddle here http://jsfiddle.net/7DWhL/
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors</title>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
var userChoice = "",
computerChoice = "",
choices = ["rock", "paper", "scissors", "lizard", "spock"];
$(document).ready( function(){
userChoice = prompt( "Do you choose rock, paper, scissors lizard or spock?" );
userChoice = userChoice.toLowerCase();
computerChoice = choices[ Math.floor( choices.length * Math.random() ) ];
$( "body" ).append( "<p>" + userChoice + "</p>" );
$( "body" ).append( "<p>" + computerChoice + "</p>" );
});
</script>
</head>
<body>
</body>
</html>
答案 1 :(得分:1)
主要问题是你得到一个无限循环,因为你在循环中设置了i = 0.2。
试试这个(小提琴:http://jsfiddle.net/5c25t/2/):
$(document).ready(function(){
var userChoice = prompt("Do you choose rock, paper, scissors lizard or spock?");
userChoice = userChoice.toLowerCase();
var computerChoice = function(){
var choices = ["rock", "paper", "scissors", "lizard", "spock"];
var random = Math.random();
var loop = true;
var i = 0.2;
var j = 0;
while (true){
if (random <= i){
return choices[j]
}
else {
i=i+ 0.2;
j++;
}
}
return choices;
};
$("body").append(userChoice);
$("body").append(computerChoice());
});