javascript - 从 jquery 范围调用到类函数
问题描述
我想从 Jquery 范围(在同一个类中)调用同一个类函数/方法。我该怎么办?
我试过了:
displayTemplate.findWithAttr(action);
或者
this.findWithAttr(action);
回复
“this.findWithAttr 不是函数”
这是我的代码。
class displayTemplate{
findWithAttr(action) {
//to do something with action
}
router(action){
if(action == "something"){
$( "#confirm_dialog_msg" ).text("text?");
$( "#dialog-confirm" ).dialog({
buttons: {
"yes": function() {
$( this ).dialog( "close" );
//how in this area call to "findWithAttr" function above?
this.findWithAttr(action);
},
"No": function() {
//..
}
}
});
}
//...
}
}
解决方案
在进入函数的 JQuery 范围之前,声明一个像这样的变量
var self = this;
然后就去做self.findWithAttr
,这应该有效。
就像:
router(action){
if(action == "something"){
var self = this;
$( "#confirm_dialog_msg" ).text("text?");
$( "#dialog-confirm" ).dialog({
buttons: {
"yes": function() {
$( this ).dialog( "close" );
//how in this area call to "findWithAttr" function above?
self.findWithAttr(action);
},
"No": function() {
//..
}
}
});
}
希望这有帮助。