2009-05-27 46 views
5

我正在使用jQuery,并且我有一个用作事件回调的函数,所以在该函数中,“this”表示捕获该事件的对象。但是,有一个实例需要从另一个函数明确调用函数 - 在这种情况下,如何设置函数内的“this”等于什么?在调用Javascript函数时,如何设置“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 
    } 
} 

回答

12

使用applycall

handleEvent.call(this, e); 
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); 
    } 
} 
+0

LOLZ ...我喜欢它。很好的解决方法。 – simplyharsh 2009-05-27 13:10:39

+2

我不敢相信人们对帕特里克的回答感到满意,这正是原始问题所需要的。这就是jQuery如何在它调用的代码中分配“this”关键字,并且应该如何完成。要改变一个函数的参数来容纳通过内置和通常理解的函数很容易执行的事情,就是尾巴摇摆狗的情况... – 2009-05-27 15:51:05

+2

我想这只是表明有很多人不要抱怨JavaScript,也许像jQuery这样的库的使用确保了他们的无知,因为他们没有花时间去真正理解语言本身。 – 2009-05-27 16:02:52

1

使用

e.target 
1

我建议你重新考虑你的函数作为一个jQuery插件。

但这里有一个快速修复:

handleEvent.apply(this,e) //transfers this from one scope, to another 
0

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

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