调用Javascript函数时,如何设置自定义值“this”?

我正在使用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 } } 

使用 应用 打电话 。

 handleEvent.call(this, e); 

只需参数化您感兴趣的function:

 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的click()函数的零参数版本可能会更健壮,这将触发该元素的所有单击处理程序:

 function differentEvent(event) { $("input.sad").keydown(e) { doSomeOtherProcessing(); $(this).click(); // simulate a click } }