删除用户单击的图像

Removing images that a user has clicked on

本文关键字:图像 单击 用户 删除      更新时间:2023-09-26

我正在开发一个内存匹配游戏。我有一些代码可以检查用户单击的两个图像是否具有相同的来源,如果它们具有相同的来源,则删除这些图像。

(function compareClicked() {
    var lastclicked = "";
    $("img").click(function() {
        var path = $(this).attr("src");
        if( lastclicked == path) {
            $('img').hide(1000, function () {
            $(this).remove();
             });
        }
        else {
            if( lastclicked != "") alert("Not a match");
        }
        lastclicked = path;
    });
})();

但是,如您所见,当它们具有相同的来源时,它会删除页面上的所有图像 - 即使用户没有单击任何图像。如何更改它,使其仅删除用户单击的两个图像?

var lastclicked = "";
$("img").click(function() {
    var path = $(this).attr("src"); // or this.src
    if (lastclicked == path) {
        $(this).hide(1000, function() {
            // remove image with same src as lastClicked
            $('img[src="' + lastclicked + '"]').remove();
        });
    } else {
        if (lastclicked != "") alert("Not a match");
    }
    lastclicked = path;
});

演示

像这样的东西怎么样

var lastEl = null;
$(document).ready(function(){
$('img').each(function(index){
  $(this).attr('id','img-' + index);
});    
$('img').click(function(){
  if( lastEl ) {
    if( ($(this).attr('src') == lastEl.attr('src')) && ($(this).attr('id') != lastEl.attr('id')) ) {
      $(this).remove();
      lastEl.remove();
    }
    lastEl = null;
  } else {
    lastEl = $(this);
  }
});
});

还没有测试过,但它必须非常接近

编辑:根据下面的对话更新了代码。JS小提琴在这里 http://jsfiddle.net/joevallender/pc3Qa/3/

再次编辑:JS小提琴链接现在应该是正确的

如果你多次(超过两次)同一个 Src,我真的建议你tag你点击的图像,知道应该隐藏哪一个。如前所述,您可以使用attr或特殊class来实现此目的。