如何查看两个图像源是否相等?

Jon*_*Jon 2 javascript jquery

我试图看看用户点击的两个图像是否相同.我有一些代码可以检索被点击的图像的来源:

$('img').click(function() { var path = $(this).attr('src'); });

我只需要一种方法来比较两个来源.我尝试将数据源存储在一个数组中,看看它们是否相等,但我无法让它工作:

var bothPaths = [];

$('img').click(function() {
    var path = $(this).attr('src');
    bothPaths.push(path);
}); 

if (bothPaths[0] == bothPaths[1]) {
    alert("they match.");
} else {
    alert("they don't match.");
}
Run Code Online (Sandbox Code Playgroud)

我会假设这会比较用户点击的前两个图像源,但我似乎在某个地方有问题.

Nie*_*sol 6

您在点击任何内容之前检查路径是否匹配.

相反,试试这个:

(function() {
    var lastclicked = "";
    $("img").click(function() {
        var path = $(this).attr("src");
        if( lastclicked == path) {
            alert("Match!");
        }
        else {
            if( lastclicked != "") alert("No match...");
        }
        lastclicked = path;
    });
})();
Run Code Online (Sandbox Code Playgroud)