JQuery - parent "this"

$('form').each(function(){ var form = this; $('a', this).click(function(){ form.submit(); }); }); 

Is there a way to get the parent ( this ) element inside this click function without using an intermediate variable? I thought that perhaps there is a keyword that I don’t know about that allows you to do this.

The $ .ajax function has a context paramters that allows you to do something like this.

+8
jquery jquery-plugins jquery-selectors
source share
5 answers

No, you did it in the best way. The Convention proposes to use this:

 var that = this; $('a', this).click(function(){ that.submit(); }); 
+7
source share

since a is a child of form , you can use closest :

 $('a', this).click(function(){ $(this).closest('form').submit(); }); 

Another proxy option:

 $('a', this).click($.proxy(function(){ this.submit(); }, this)); 
+2
source share

Of course - use closure.

 $('form').each(function() { $('a', this).click((function(x) { return function() { x.submit(); })(this)); }); 

If you have a curry function (similar to the one specified in Prototype, not sure if it is built into jQuery), you can simplify this middle line a bit:

 $('a', this).click(curry(function(x) { x.submit(); }, this)); 
+2
source share

Firstly, your example is correct, and secondly, as most people do. There is no keyword, just the reverse direction and intersection of the DOM for the most likely parent (which is stupid since you already found it, right?). In this case, I would recommend an intermediate variable, even if the other responder correctly showed how to use closest . (In addition, he relies on some technical information that <form> inside a <form> is invalid HTML. There is no guarantee for things like <div> that it does not cross any child <div> that is looking for next <a> .)

In jQuery you will see many things like this:

 $("#parent").something(function() { var _this = this; // var self = this; // var that = this; // var someMoreMeaningfulName = this; $("#child", this).somethingElse(function() { $(_this).somethingEvenElser(); ... }); }); 

This is not the prettiest thing to read, but the pattern happens often enough to be easily recognized. I recommend a little what you do ( var form ), and not as the tag _this (underscore can mean private variables), self (actually it is not), etc.

+2
source share

You should be able to reference it with the jquery parent (or parents, depending on how the tag is nested) selector

So something like this should work:

 $('form').each(function(){ $('a', $(this)).click(function(){ $(this).parent('form').submit(); }); }); 
+1
source share

All Articles