我试图在JavaScript中创建一个类似于“Whack-a-Mole”游戏的程序。除了一件事,我发现了一切。如果没有点击,我想让每个“痣”在短暂的时间后消失。生成痣的函数如下所示。我不完全确定如何隐藏痣,但我想通过一个唯一生成的ID选择它们,如代码所示。有一个全局变量“count”,用于生成每个ID。
function addMole(){
var yPos = numOne();
var xPos = numTwo();
if (timeLeft > 0){
$("#gamespace").append('<img id="i'+count+'" src="img/mole.gif" style="top:'+yPos+'px;left:'+xPos+'px;" />');
count++;
setTimeout("addMole()", Math.floor(Math.random()*2000));
};
};
我尝试过使用此功能,但它似乎没有做任何事情,我不确定如何或在何处调用它,或者我是否使用正确的选择器。
function noMole(){
$("#i"+count).delay(2000).hide();
};
答案 0 :(得分:0)
我可能会选择以下内容:
function addMole() {
var yPos = numOne();
var xPos = numTwo();
if (timeLeft > 0) {
//make a new mole and have a reference to it
var newMole = $('<img src="img/mole.gif" style="top:' + yPos + 'px;left:' + xPos + 'px;" />');
//put the mole in the game
$("#gamespace").append(newMole);
//add another mole in a random amount of time
setTimeout(addMole, Math.floor(Math.random() * 2000));
//remove the created mole after 5 seconds
setTimeout(function(){ newMole.remove(); }, 5000);
};
};
&#13;
您不需要查找。你只需要参考。