How do I reference the outer “$(this)” in jquery?

2019-07-04 15:07发布

Let's say I have code like this:

$('.myClass').each(function(){
    $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){
        doSomething($(this));
    });
});

The $(this) that I pass to the doSomething function is what's in the second jquery parenthesis - $('#' + $(this).attr('id') + "_Suffix"). How do I reference what's in the first parenthesis - what the original this referred to? ( $('.myClass').each )

I assume I could save it into a variable, and then use that variable:

$('.myClass').each(function(){
    outerThis = $(this);
    $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){
        doSomething($(outerThis));
    });
});

But is there any way to reference it without doing this?

标签: jquery this
3条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-04 15:26

You need to put it in a separate variable:

$('.myClass').each(function(){
    var outer = $(this);
    $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){
        doSomething(outer);
    });
});

Also, livequery is deprecated; you should use live instead.

查看更多
smile是对你的礼貌
3楼-- · 2019-07-04 15:38

Try to use local variable

 $('.myClass').each(function(){
    var myclassObj = $(this);
        $('#' + myclassObj.attr('id') + "_Suffix").livequery('click', function(){
            doSomething($(this));
        });
    });
查看更多
▲ chillily
4楼-- · 2019-07-04 15:40

Just save the scope in local variable:

$('.myClass').each(function(){
    var self = $(this);
    $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){
        doSomething($(this));
    });
});
查看更多
登录 后发表回答