我正在研究记忆匹配游戏.我有一些代码检查用户点击的两个图像是否具有相同的源,如果它们具有相同的源,则删除图像.
(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;
});
})();
Run Code Online (Sandbox Code Playgroud)
但是,正如您所看到的,当它们具有相同的源时,它会删除页面上的所有图像 - 即使用户没有单击它们.如何更改它以便仅删除用户单击的两个图像?
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;
});
Run Code Online (Sandbox Code Playgroud)