2012-06-18 33 views
2

我想看看用戶點擊的兩個圖像是否相同。 我有一些代碼,獲取被點擊圖像的來源:如何查看兩個圖像源是否相同?

$('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."); 
} 

我會假設,這會比前兩個圖像源的用戶點擊,但我似乎在某個地方有問題。

回答

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

你的if語句在加載時僅解釋,試試這個:點擊圖像後

var bothPaths = []; 

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

function compare() { 
    if (bothPaths[0] == bothPaths[1]) { 
     alert("they match."); 
    } else { 
     alert("they don't match."); 
    } 
} 
0

你的點擊處理程序添加的東西到陣列。您的比較恰好在您的點擊處理程序被連接後發生。換句話說,在任何人有機會點擊任何東西之前,你會比較數組中的前兩個位置。

這是您應該學習的一些最佳實踐代碼。它將幫助您瞭解頁面的生命週期以及jQuery如何與其進行最佳交互。

$(document).ready(function(){ 
    var lastClicked = ''; 
    $(document).on('click', 'img', function(){ 
     var src = $(this).attr('src'); 
     if (src == lastClicked) { 
      alert('matching'); 
     } else { 
      lastClicked = src; 
     } 
    }); 
});