JQuery:通过生成的ID隐藏动态添加的图像

时间:2017-12-07 22:40:46

标签: javascript jquery

我试图在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();

};

1 个答案:

答案 0 :(得分:0)

我可能会选择以下内容:

&#13;
&#13;
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;
&#13;
&#13;

您不需要查找。你只需要参考。