我正在尝试这样做:
var foo = new Foo();
foo.setEvents( foo );
foo的代码:
function Foo()
{
this.id = getId(); //this works successfully, each instance of foo gets
//assigned a new auto incrementing id e.g 1, 2, 3, etc
this.setEvents = function( that )
{
$("#myButton").click( that.bar );
}
this.bar = function()
{
alert(this.id);
}
}
每当我运行此代码并单击按钮时,我都会收到一条警告,提示“未定义”
如何在事件触发时保留要运行其方法的对象的状态?
最佳答案
这指的是 jQuery 范围内的不同内容...
function Foo()
{
obj=this;
this.id = 1; //this works successfully, each instance of foo gets
//assigned a new auto incrementing id e.g 1, 2, 3, etc
this.setEvents = function( that )
{
$("#myButton").click( that.bar );
}
this.bar = function()
{
console.log(obj)
}
}
var foo = new Foo();
foo.setEvents( foo );
关于javascript - Jquery 事件和对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462334/