简体   繁体   中英

JQuery: Hiding dynamically added images via generated ID

I am trying to make a program in JavaScript that functions similar to a "Whack-a-Mole" game. I have everything figured out except for one thing. I would like to have each "mole" disappear after a brief time if it is not clicked on. The function that generates the moles is shown below. I am not entirely sure how to go about hiding the moles, but I would like to do so by selecting them by a uniquely generated ID, as shown in the code. There is a global variable "count" that is used to generate each 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));
};
};

I have tried using this function, but it doesn't seem to do anything and I'm not sure how or where to call it or if I'm even using the right selector.

function noMole(){
$("#i"+count).delay(2000).hide();

};

I'd probably go with something like the following:

 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); }; }; 

You don't need a lookup. You just need the reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM