简体   繁体   中英

How to reference jQuery object inside of it's own method call?

I'm trying to do this:

$('.summary').css('top',$(this).outerHeight());

Where I reference 'this' I would like to reference the instance of $('.summary') that jquery is currently talking to, since there are multiple, but the scope considers 'this' the page in this instance.

What's the easiest way to reference each element in this case?

I looked through the search for the answer for this, but don't quite know the right phrasing. If this has been answered let me know and I can close as a duplicate.

Thanks!

You can pass a function directly to .css() .

$('.summary').css('top',function() {
    return $(this).outerHeight();
});

It will iterate the elements, and the return values will be the new values for 'top' .

You're looking for .each() , I think.

$('.summary').each(function() {
    var $this = $(this);
    $this.css('top', $this.outerHeight());
});

EDIT: Less requerying. Also, I like am not i am 's answer more. It's slightly more elegant.

You should define it as a variable first, then you can reference it in the method:

var summary = $('.summary');
summary.css('top',summary.outerHeight());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM