如何在jquery中的单击事件的处理程序中获取对象的内容? [英] How to get the this of a object in a handler for a click event in jquery?
本文介绍了如何在jquery中的单击事件的处理程序中获取对象的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// begin signals
this.loginSignal
this.init = function(){
// init signals
this.loginSignal = new t.store.helpers.Signal;
// map events
$('[value]="login"', this.node).click(this.login)
}
this.login = function(){
// this will dispatch an event that will be catched by the controller
// but this is not refering to this class
// and the next line fails :s
this.loginSignal.dispatch();
}
要使其正常工作,我必须添加
to make it work now i must add
var $this = this;
此行,并使用$this
代替this
:S
this line and use $this
instead of this
:S
有什么更清晰的方法吗? 谢谢
any clearer way around? thanks
推荐答案
调用点击处理程序时,this
关键字将重新映射到触发事件的元素.要到达原始对象,您需要将函数代码放在闭包中,并在闭包外部引用该对象,在该对象中您仍具有对this
的正确引用.
When the click handler is called, the this
keyword is remapped to the element that triggered the event. To get to the original object, you want to put the function code in a closure, and make a reference to the object outside the closure, where you still have the correct reference to this
.
// map events
var thisObject = this;
$('[value]="login"', this.node).click(function () {
thisObject.loginSignal.dispatch();
});
这篇关于如何在jquery中的单击事件的处理程序中获取对象的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文