我正在尝试从Jquery对话框Ok按钮调用一个函数。
我试过这两种方法,
1
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();}}
});2
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做到这一点!!
谢谢!
发布于 2010-11-29 01:50:48
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();}}
});发布于 2010-11-29 01:55:37
这里不需要另一个引用,只需直接引用函数,就像"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是一个不同的上下文。
发布于 2010-11-29 01:49:05
在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(); } }
});
};https://stackoverflow.com/questions/4298087
复制相似问题