我试图在JQuery中创建一个while循环
$(document).ready(function () {
//startgame();
var game = {
started: false,
jumper: 0, //player jump active or not
seconds: 0
}
$('body').keyup(function (space) {
if (space.keyCode == 32) { //32 = spatie
if (game.started != true) { //set game to started
game.started = true;
console.log("game started? " + game.started);
};
if (game.jumper == 0) { //start jump
game.jumper = 1; //jump is in action
$("#player").animate({ //animate to air
top: "-=75"
}, 250, function () {
$(this).animate({ //return to ground
top: "+=75"
}, 500, function () {
game.jumper = 0;
});
});
}
}
}); //end space
//not even running this code
while (game.started == "true") {
var squaretimer = Math.random(1000, 3000);
console.log(squaretimer);
$("#border").append("<div class='driehoek'></div>");
}
});
控制台中没有错误。 所以这个想法最终是代码产生的(随机的1/3秒新的div) 但整个循环都没有运行。我做错了吗?
答案 0 :(得分:1)
您正在将布尔值与字符串进行比较,您应该执行以下操作:
while(game.started){
....
}
<强>更新强> 另外,在开始游戏之前,立即调用循环。你需要立即执行它。你可以:
将循环放在函数中:
function startLoop() {
while (game.started) {
var squaretimer = Math.random(1000, 3000);
console.log(squaretimer);
$("#border").append("<div class='driehoek'></div>");
}
}
然后在你开始游戏时调用它:
$('body').keyup(function (space) {
if (space.keyCode == 32) { //32 = spatie
if (game.started != true) { //set game to started
game.started = true;
console.log("game started? " + game.started);
startLoop();
};
if (game.jumper == 0) { //start jump
game.jumper = 1; //jump is in action
$("#player").animate({ //animate to air
top: "-=75"
}, 250, function () {
$(this).animate({ //return to ground
top: "+=75"
}, 500, function () {
game.jumper = 0;
});
});
}
}
}); //end space
希望这有帮助。
答案 1 :(得分:0)
尝试这样的事情。
$(document).ready(function () {
//startgame();
var game = {
started: false,
jumper: 0, //player jump active or not
seconds: 0
}
$('body').keyup(function (space) {
if (space.keyCode == 32) { //32 = spatie
if (game.started != true) { //set game to started
game.started = true;
console.log("game started? " + game.started);
};
if (game.jumper == 0) { //start jump
game.jumper = 1; //jump is in action
$("#player").animate({ //animate to air
top: "-=75"
}, 250, function () {
$(this).animate({ //return to ground
top: "+=75"
}, 500, function () {
game.jumper = 0;
});
});
}
}
}); //end space
//not even running this code
while (game.started) {
var squaretimer = Math.random(1000, 3000);
console.log(squaretimer);
$("#border").append("<div class='driehoek'></div>");
}
});
答案 2 :(得分:0)
$(body).keyup(function(space) {
//your code
someFunction(game.started);
});
function someFunction(a) {
this.a = a;
while (this.a) {
// your code again
}
}
// The purpose of calling function is that it binds in keyup event
答案 3 :(得分:0)
while (game.started == "true")
应该是
while (game.started == true)