5

私はjQueryを使用しており、イベントコールバックとして機能する関数があるため、その関数では、「this」はイベントをキャプチャしたオブジェクトを表します. ただし、関数を別の関数から明示的に呼び出したい場合があります。この場合、関数内で「これ」が等しいものを設定するにはどうすればよいですか?

例えば:

function handleEvent(event) {
    $(this).removeClass("sad").addClass("happy");
}

$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        handleEvent(e); // in this case, "this" will be the window object
                        // but I'd like to set it to be, say, the input in question
    }
}
4

5 に答える 5

13

使用する申し込み を呼び出します

handleEvent.call(this, e);
于 2009-05-27T13:09:20.363 に答える
4

興味のある関数をパラメータ化するだけです。

function doStuff(el) {
    $(el).removeClass("sad").addClass("happy");
}

function handleEvent(event) {
    doStuff(this);
}

$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        doStuff(this);
    }
}
于 2009-05-27T13:06:15.677 に答える
1

使用する

e.target
于 2009-05-27T13:06:37.750 に答える
1

関数をjQueryプラグインとしてリファクタリングすることをお勧めします。

しかし、ここに簡単な修正があります:

handleEvent.apply(this,e) //transfers this from one scope, to another
于 2009-05-27T13:10:31.157 に答える