I am trying to see if two images that the user clicked on are the same. I have some code that retrieves the source of an image that was clicked on:
$('img').click(function() {
var path = $(this).attr('src');
});
I just need a way to pare two sources with each other. I tried storing the sources in an array and seeing if they were equal but I couldn't get that to work:
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.");
}
I would assume that this would pare the first two image sources that the user clicked on but I seem to have a problem somewhere.
I am trying to see if two images that the user clicked on are the same. I have some code that retrieves the source of an image that was clicked on:
$('img').click(function() {
var path = $(this).attr('src');
});
I just need a way to pare two sources with each other. I tried storing the sources in an array and seeing if they were equal but I couldn't get that to work:
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.");
}
I would assume that this would pare the first two image sources that the user clicked on but I seem to have a problem somewhere.
Share Improve this question asked Jun 18, 2012 at 19:23 JonJon 9768 silver badges23 bronze badges3 Answers
Reset to default 6You're checking if the paths match... before anything has been clicked.
Instead, try this:
(function() {
var lastclicked = "";
$("img").click(function() {
var path = $(this).attr("src");
if( lastclicked == path) {
alert("Match!");
}
else {
if( lastclicked != "") alert("No match...");
}
lastclicked = path;
});
})();
your if statement is interpreted only at load time, try this:
var bothPaths = [];
$('img').click(function() {
var path = $(this).attr('src');
bothPaths.push(path);
pare()
});
function pare() {
if (bothPaths[0] == bothPaths[1]) {
alert("they match.");
} else {
alert("they don't match.");
}
}
Your click handler adds things to the array after your image is clicked. Your parison happens right after your click handler is attached. In other words, you pare the first two places in the array before anyone has a chance to click on anything.
Here's some best practice code that you should study. It will help you understand the lifecycle of a page and how jQuery best interacts with it.
$(document).ready(function(){
var lastClicked = '';
$(document).on('click', 'img', function(){
var src = $(this).attr('src');
if (src == lastClicked) {
alert('matching');
} else {
lastClicked = src;
}
});
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745426079a4627183.html
评论列表(0条)