我正在尝试从Jquery对话框Ok
按钮调用一个函数。
我尝试了这两种方法,
this.commentDialog = function(){
$("#commentDialog").dialog( "destroy" );
html = "<div id='cmtDialog'>";
html += "Comment<textarea id='comment'></textarea></div>";
$("#commentDialog").html(html);
$("#commentDialog").dialog({
title:"Search Result",
bgiframe: true,
height: 'auto',
width: 'auto',
modal: true,autoOpen: true,
buttons: { "Ok": function() { this.saveComment();}}
});
this.commentDialog = function(){
$("#commentDialog").dialog( "destroy" );
html = "<div id='cmtDialog'>";
html += "Comment<textarea id='comment'></textarea></div>";
$("#commentDialog").html(html);
$("#commentDialog").dialog({
title:"Search Result",
bgiframe: true,
height: 'auto',
width: 'auto',
modal: true,autoOpen: true,
buttons: { "Ok": function() { saveComment();}}
});
两者都不起作用!
我如何使用jquery !!
感谢!!!
答案 0 :(得分:5)
this.commentDialog = function(){
// save a reference of "this" and use it later.
var me = this;
$("#commentDialog").dialog( "destroy" );
html = "<div id='cmtDialog'>";
html += "Comment<textarea id='comment'></textarea></div>";
$("#commentDialog").html(html);
$("#commentDialog").dialog({
title:"Search Result",
bgiframe: true,
height: 'auto',
width: 'auto',
modal: true,autoOpen: true,
buttons: { "Ok": function() {
// use me instead of this, as this now refers to the function.
me.saveComment();}}
});
答案 1 :(得分:3)
这里不需要另外的引用,只需直接引用函数"Ok"
绑定,如下所示:
this.commentDialog = function(){
$("#commentDialog").dialog( "destroy" );
html = "<div id='cmtDialog'>";
html += "Comment<textarea id='comment'></textarea></div>";
$("#commentDialog").html(html);
$("#commentDialog").dialog({
title:"Search Result",
bgiframe: true,
height: 'auto',
width: 'auto',
modal: true,autoOpen: true,
buttons: { "Ok": this.saveComment }
});
};
这样你就不会进入另一个匿名函数,其中this
是一个不同的上下文。
答案 2 :(得分:2)
在Ok
回调中,this
并非您认为的那样。
您需要保存对原始this
的引用。
this.commentDialog = function() {
var html = "<div id='cmtDialog'>Comment<textarea id='comment'></textarea></div>";
var me = this; //Save the original this
$("#commentDialog")
.dialog( "destroy" )
.html(html);
.dialog({
title:"Search Result",
bgiframe: true,
height: 'auto',
width: 'auto',
modal: true,autoOpen: true,
buttons: { "Ok": function() { me.saveComment(); } }
});
};