jQuery $(this)问题

sha*_*jia 3 jquery this

我写了一些jQuery代码如下:

$('.button').each(function(){
    $(this).click(function(){
        console.log($(this));
        do_sth();
    });
});

var do_sth = function(){
    console.log($(this));
}
Run Code Online (Sandbox Code Playgroud)

我希望console.log结果是一样的,但是它工作错误...第一个引用了一个HTMLElement,但第二个引用了DOMWindow ...我怎么能重写do_sth函数使它们都引用HTMLElement?谢谢.

ale*_*lex 9

你可以......

do_sth.call(this);
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用jQuery的proxy()方法.

$.proxy(do_sth, this)();
Run Code Online (Sandbox Code Playgroud)

jsFiddle.