Alex
Alex

Reputation: 26624

$(this) is null inside .click(function(){...}), why?

I've got this jquery code, that allows me to click on a link to fetch its parent and change some value in another place:

$("a.menu_filter_select").click(function(){
  var parent_filter = $(this).parent("tr");
  // Update value
  parent_filter.find(".filter_value").html($(this).html());
});

The problem is that it gets a null value on $(this), that's an unexpected behavior, I don't understand why it doesn't work, any idea?

Here is the console debug with a breakpoint inside the method:

$(this)
> null
this
> <a class=​"menu_filter_select" href=​"http:​/​/​localhost:​3000/​#" rel=​"1">​test</a>​

Upvotes: 4

Views: 5298

Answers (4)

Karl Gohery
Karl Gohery

Reputation: 124

Personally I always use $ when using jquery, but I have seen this happen where I included a plugin which used jquery rather than $. For some reason it doesn't like using both, but just changing the jquery to $ in the plugin code sorted it out for me.

Upvotes: 0

Guffa
Guffa

Reputation: 700910

The only reason I can think of for that to happen, is that the identifier $ has been redefined.

You can check if $ == jQuery in the function. If it's not, then you probably have included another script that uses the $ identifier too.

There is a compatibility mode for jQuery to be used if there is another library that also uses that identifier, where it returns the value of the $ identifier to it's original value, and you use the jQuery identifier instead.

Upvotes: 2

culebr&#243;n
culebr&#243;n

Reputation: 36563

I think it's because your function receives an event as an argument, and you need event.target.

$('a.menu_filter_select').click(function(evt) {
    var parent_filter = $(evt.target).closest('tr');

I also recommend using closest instead of parent, since your code will work even if someone puts <b>, <i> or <span> around the anchor. I also use find instead of child.

Edit: in fact, this in FireFox refers to the anchor object, but I can't for sure if it's implemented the same way in other browsers. BUT event.target can refer to the child object if, say the document is like this:

<a><b>some text</b> other text</a>

then this event handler can output different elements:

$(a).click(function(event) { console.log(this, event.target); });

Try running this code in FireBug, see how it works.

Upvotes: 4

Zack Bloom
Zack Bloom

Reputation: 8427

Occasionally the binding between $ and jQuery can fail, try replacing the $ with jQuery.

Also try using $.log rather than a breakpoint to ensure that the scope of the this is not changing.

Upvotes: 0

Related Questions