我有一个自己的js-class并尝试在点击事件中使用 jquery的$(this)和object-this. jquery的$(this)工作正常,但是对象 – 这没有定义. http://jsfiddle.net/j33Fx/2/ var myclass = function(){ this.myfunction = function(
jquery的$(this)工作正常,但是对象 – 这没有定义.
http://jsfiddle.net/j33Fx/2/
var myclass = function(){
this.myfunction = function(){
alert('myfunction');
}
this.buttonclicked = function(){
alert('buttonclicked');
}
this.writeout = function(){
var buttoncode = '<button class="mybutton">click</button>';
$('body').append(buttoncode);
$('.mybutton').click(function(){
alert('Button: '+$(this).attr('class'));
this.buttonclicked();
});
this.myfunction();
}
}
var x = new myclass();
x.writeout();
当我单击附加按钮时,我得到一个带有Button类名的警报,但我的函数“this.buttonclicked”似乎不是一个函数.
有任何想法吗?
这指的是在事件处理程序中调用事件的元素.您可以将当前对象缓存在其他变量中.哪个可以用于后者.使用
this.writeout = function(){
var buttoncode = '<button class="mybutton">click</button>';
$('body').append(buttoncode);
var _self = this; //cache current object
$('.mybutton').click(function(){
alert('Button: '+ $(this).attr('class')); //Here this refers to element which invoked the event.
_self.buttonclicked(); //Use cached object
});
this.myfunction();
}
Updated Fiddle
