我有一个自己的 js 类,并尝试在点击事件中使用 jquery 的 $(this) 和 object-this 。
jquery 的 $(this) 工作正常,但对象-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();
当我单击附加按钮时,我收到带有按钮类名的警报,但我的函数“this.buttonclicked”似乎不是一个函数。
有任何想法吗?
this
指在事件处理程序中调用事件的元素。您可以将当前对象缓存在其他变量中。后者可以使用。
use
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();
}
更新了小提琴
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)