jQuery Get the original context from a find
If I want to fetch a f开发者_开发问答orm, then grab some button, then attach some action to that button that submits my form, I'm currently doing it like so:
<form>
<button>Some Button</button>
</form>
$('form').find('button').click(function(){
$(this).closest('form').submit(); // is there a better way of getting the form?
});
I'm wondering if there's a more performant way of selecting the original form element within my find. Instead of having to traverse back up the dom, is there any way to get the reference to my original form
object inside the click event of its decendant?
Unfortunately .context
will give me the button
element in this case, any way i can get the original context? Or do I just have to traverse up?
Note that this is a contrived example, i'm not actually using buttons and forms, but I'm more interested in fetching the original context within a find
.
I think the point is to cache the first call? Just run it through an each(), which will allow you to store context in that's method's parameters.
$('form').each(function(idx,el){
$(this).find('button').click(function(){
$(el).submit();
});
});
This depends what you're trying to do. If you're within an event callback, no, there is no way of getting the original selection. The only data you have is which element was clicked, and a few details about the click event itself. Don't forget that form
there can match multiple different elements, so knowing which one you should be matching is impossible. (Unless there's only one -- but it still isn't a very stable way of coding your site.)
If you're just in a standard method chaining context, you can use end
to go one stage back in the search:
$('form').find('button').prop({name: 'foo', value: 'bar'}).end().submit();
If you only have the one form then you could do something like this:
var $form = $('form');
$form.find('button').click(function() {
$form.submit();
});
Just compute the $('form')
once and use it as needed.
I doubt that $(this).closest('form')
is really going to be all that expensive though. OTOH, good habits are good habits and not computing the same thing over and over again is usually a good habit.
As far as I know, there is no way to reference the search object from the found object. This is because you'll only get the JQuery object that was found, not information from the function that was called to find it:
var blah = $('blah');
//The following variable will have no direct reference to blah, but
//blah can still be used if it stays in scope:
var thingWithNoReferenceToBlah = blah.find('thing');
精彩评论