Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

target previous $this

Tags:

jquery

How do I target $this (from 'each' context) from inside 'click' function. I want to remove awkward .parents().find() code.

$('.layout.responsive').each(function () {
    $('.area.optional', this).before('<a href="#" class="toggle_responsive" onClick="return false">Show details</p>').hide();
    $('.toggle_responsive', this).click(function () {
        $(this).parents('.layout.responsive').find('.area.optional').toggle();
    });
});
like image 246
henrijs Avatar asked Nov 15 '10 02:11

henrijs


2 Answers

Save it in a named (non-special) variable:

$('.layout.responsive').each(function () {
    var area = $('.area.optional', this).before('<a href="#" class="toggle_responsive" onClick="return false">Show details</p>').hide();
    $('.toggle_responsive', this).click(function () {
        $(area).toggle();
    });
});
like image 197
Gareth Avatar answered Oct 21 '22 11:10

Gareth


You can simply store it in a variable:

$('.layout.responsive').each(function () {
    var $elem = $('.area.optional', this).before('<a href="#" class="toggle_responsive">Show details</p>').hide();
    $('.toggle_responsive', this).click(function(e) {
        e.preventDefault();
        $elem.toggle();
    });
});

Also note the e.preventDefault(); call which does pretty much what your onclick="return false;" did but in a much cleaner way.

like image 45
ThiefMaster Avatar answered Oct 21 '22 10:10

ThiefMaster