JQuery/JavaScript 隐藏一个被点击的元素而不是其他元素

JQuery/JavaScript hide one clicked element but not others

我正在创建一个 JavaScript 和 JQuery "Whack-a-Mole" 游戏,并且我每两秒将随机坐标的 "mole" 图像附加到游戏空间中。单击痣时,我希望它隐藏(从屏幕上消失)。但是,按照我现在编写代码的方式,单击一个痣会导致所有痣图像被隐藏。很想听听关于仅选择和隐藏单击的痣图像而不隐藏其他痣图像的任何想法。

这是我的 "addMole" 函数:

function addMole() {
    xPos = randPosX();
    yPos = randPosY();
    $('#gamespace').append('<img src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole'); // insert mole into #gamespace
    repeatAddMole = setTimeout("addMole()", 2000); // append moles every 2 seconds
};

这是游戏的主要功能:

$(document).ready(function() {
    $('#start_button').click(function() { 
        start();
        $('#timer').show(); // show timer
        $('.mole').on("click", function(){
            incScore();
            $('img', this).hide();
        });
    });

谢谢!

你可以这样做:

$('#gamespace').append('<img onclick="this.style.display=\'none\'" src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole'); // insert mole into #gamespace

您正在将 mole class 添加到 #gamespace,而不是图像。也许你想要这个:

$('#gamespace').append($('<img src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole'));

这里有一个演示可以帮助您 https://jsfiddle.net/bradlis7/ubar2Lzb/1/。我喜欢让函数按照他们说的去做(addMole 不应该真的设置一个新的计时器)。

此外,问题还在于您在单击开始之前仅将事件附加到创建的图像(痣)。 您可以使用事件 delegation。在开始按钮单击处理程序之外使用此代码。

$( "#gamespace" ).on( "click", "img", function( event ) {
  incScore();
  $(this).hide();
});

我会用这种方式做:

function addMole() {
   xPos = randPosX();
   yPos = randPosY();

   var el = $('#gamespace').append('<img src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole'); 
   el.on("click", function(){
       $(this).remove();
       incScore();
   });
   repeatAddMole = setTimeout("addMole()", 2000); 
};

追加函数 returns 你 jQuery 追加元素的对象,所以你可以在创建后直接在其上附加事件。如果您在创建对象之前创建事件,则事件不会附加到它。这样,您创建元素然后附加事件。

你可以按照 mhodges 在他的评论中写的方式来做,但我只是不喜欢这种方式,因为我认为它效率不高。