5

我正在使用 jQuery,并且我有一个用作事件回调的函数,因此在该函数中,“this”表示捕获事件的对象。但是,有一个实例,我想从另一个函数显式调用该函数 - 在这种情况下,如何设置函数中的“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 回答
0

如果您只是想像正常触发一样调用单个事件处理程序,apply/call将正常工作。但是,根据您的需要,使用 jQuery 的click()函数的零参数版本可能更健壮,这将触发该元素的所有点击处理程序:

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        $(this).click(); // simulate a click
    }
}
于 2009-05-27T18:34:20.553 回答