Reputation: 1181
Using Jquery, how can I say(this is within a click() function):
if(element clicked has an href == 'the href location'){
};
I was using something like this:
if ($(this).attr('href') == 'image.png') {
//Do Stuff
};
This wasn't working, because I found out that $(this) was referring to the window. Furthermore, I don't know how to make the use of $(this) specific to something.
Any help would be appreciated.
Upvotes: 1
Views: 266
Reputation: 7315
Are you seeking something like this?
$(document).ready(function() {
$('img').click(function() {
var target = $(this).attr('src');
if( target === 'http://www.mallorcaweb.net/masm/Planetas/Jupiter.jpg' ) {
alert('you have found it!');
}else{
alert('wrong one..');
}
});
});
Upvotes: 0
Reputation: 11461
If you only want to fire click events on the element that meets this condition, use:
$('a[href="image.png"]').click(function(e)
{
});
If you want to fire click events on all elements of a selector, but then do something special if they have a certain href, you had it right but $(this)
only refers to the clicked element within an event callback.
$('a').click(function(e)
{
if ($(this).attr('href') == 'image.png') { ... }; // it works within this function
});
Upvotes: 1