1

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Randomishlying
  • 1,161
  • 2
  • 9
  • 15
  • *I found out that $(this) was referring to the window*: Then the code might not be inside the event handler. Please show how/when you are making the `if` statement with regard to the click event handler. – Felix Kling Feb 09 '13 at 01:57
  • http://stackoverflow.com/questions/303956/jquery-select-a-which-href-contains-some-string – António Almeida Feb 09 '13 at 02:08

2 Answers2

1

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
 });
Plynx
  • 11,341
  • 3
  • 32
  • 33
0

Are you seeking something like this?

Here is working jsFiddle.

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

});
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • That's pretty much what I already had. Now I think the problem was that I had yet to add an if else statement, to tell it what to do when a different button was clicked. When I clicked another button, the stuff I told it to do (for the first button) stayed the same. I was thinking about the if statement in terms of, if another button doesn't meet these requirements, it won't run this function. Which is what happened, but I also didn't expect that the function ran from the previous button wouldn't disappear. Sorry to have wasted time. – Randomishlying Feb 09 '13 at 02:19