jQuery - parent "this"
$(开发者_运维问答'form').each(function(){
var form = this;
$('a', this).click(function(){ form.submit(); });
});
Is there any way I can get the parent (this
) element inside of that click function, without using a intermediate variable? I was thinking that maybe there's a keyword I'm not aware of that lets you do it.
In the $.ajax function there's a context
paramters which allows you to do something like this.
No, you have done it the best way. Convention suggests using that:
var that = this;
$('a', this).click(function(){ that.submit(); });
since a
is a child of form
, you can use closest
:
$('a', this).click(function(){ $(this).closest('form').submit(); });
Another option is proxy
:
$('a', this).click($.proxy(function(){ this.submit(); }, this));
Sure -- use a closure.
$('form').each(function() {
$('a', this).click((function(x) { return function() { x.submit(); })(this));
});
If you have a curry
function (similar to the one in Prototype, not sure if one's built into jQuery), you can simplify that middle line a bit:
$('a', this).click(curry(function(x) { x.submit(); }, this));
First off, your example is right, and secondly, it's how most people would do it. There is no keyword, just reversing direction and traversing the DOM for the most likely parent (which is silly since you've already found it, right?). That being the case, I'd recommend an intermediate variable, even if other answerer's have correctly shown how to use closest
. (Also, it relies on somewhat of a technicality, that a <form>
inside a <form>
is invalid HTML. There's no guarantee for things like a <div>
that it doesn't cross over any child <div>
s looking for the next <a>
.)
In jQuery you see a lot of stuff like this:
$("#parent").something(function() {
var _this = this;
// var self = this;
// var that = this;
// var someMoreMeaningfulName = this;
$("#child", this).somethingElse(function() {
$(_this).somethingEvenElser();
...
});
});
It's not the prettiest thing to read, but the pattern occurs frequently enough that it's easily recognizable. I somewhat recommend what you're doing (var form
) instead of stuff like _this
(underscore can imply private variables), self
(it's actually not), etc.
You should be able to refer to it with jquery's parent (or parents depending on how nested the a tag is) selector
So something like this should work:
$('form').each(function(){
$('a', $(this)).click(function(){ $(this).parent('form').submit(); });
});
精彩评论