JavaScript関数を呼び出すときに、どのように私は、「これ」のカスタム値を設定するのですか?
-
06-09-2019 - |
質問
私はjQueryのを使用していると私は、イベントコールバックとして機能し、その結果、機能の「この」イベントをキャプチャし、オブジェクトを表す機能を有しています。しかし、私は別の関数から明示的に関数を呼び出すしたい場合があります - ?どのように私は、「これは」このケースでは、関数内で等しくなるか
に設定します例
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
}
}
解決
使用<デル> 適用する デル> < href = "https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call" のrel = "noreferrerは"> を呼び出します。
handleEvent.call(this, e);
他のヒント
ちょうどあなたが興味を持っている機能をパラメータ化
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);
}
}
使用
e.target
私はjQueryのプラグインとして使用するリファクタリングあなたの関数をアドバイス思います。
しかし、ここでは簡単な修正です。
handleEvent.apply(this,e) //transfers this from one scope, to another
あなたは、単にapply
/ call
、それが正常にトリガされていたかのように単一のイベントハンドラを呼び出すために探している場合は正常に動作します。しかし、あなたのニーズに応じて、jQueryのクリックしてください()のゼロ引数バージョンを使用して、より堅牢でありトリガーするの機能、すべてその要素のハンドラをクリックします:
function differentEvent(event) {
$("input.sad").keydown(e) {
doSomeOtherProcessing();
$(this).click(); // simulate a click
}
}
所属していません StackOverflow