$(this)和此内部点击事件 [英] $(this) and this inside click-event
本文介绍了$(this)和此内部点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自己的js类,并尝试在单击事件中使用jquery的$(this)和object-this.
i have an own js-class and try to use jquery's $(this) and object-this in an click-event.
jquery的$(this)可以正常工作,但是没有定义对象this.
jquery's $(this) works fine, but the object-this is not defined.
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"似乎不是一个函数.
When i click the appended button, i get an alert with the classname of the Button, but my function "this.buttonclicked" seems not to be a function.
有什么想法吗?
推荐答案
this
是指在事件处理程序中调用事件的元素.您可以将当前对象缓存在其他变量中.以后可以使用.
this
refers to element which invoked the event in the event handler. You can cache current object in some other variable. Which can be used latter.
使用
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();
}
这篇关于$(this)和此内部点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文