我正在使用jquery ui对话框,我从jquery ui网站下载它,版本是jquery-ui-1.10.2.custom.min.js,jquery是jquery-1.9.1.js,它与jquery ui js捆绑在一起,但是现在我遇到一个问题:打开对话框并点击保存按钮,我想要关闭对话框,这里是我的代码:
- $(function(){
- $("#dialog-form").dialog({
- autoOpen: false,height: 350,width: 450,modal: true,buttons: {
- "save": function() {
- if(!checkDept()){
- return ;
- }
- $.post('dept_save.do',{'dept.deptId':$("#dialog_dept_deptId").val(),'dept.deptName':$("#dialog_dept_deptName").val(),'dept.manager':$("#dialog_dept_manager").val(),},function(data,status,xhr){
- if(status == 'success'){
- alert('save success');
- $(this).dialog("close");
- }else{
- alert('error:'+data);
- }
- },"json");
- }
- },close: function() {
- $(this).dialog("close");
- }
- });
- /* to open dialog*/
- $("#add").click(function(){
- $("#dialog-form").dialog("open");
- });
现在当我关闭“保存成功”弹出对话框时,对话框对话框未关闭,并发生错误:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method ‘close’ jquery-1.9.1.js:507.
还有另一个错误:
Uncaught SyntaxError: Unexpected token o jquery-1.9.1.js:541
谢谢。
解决方法
一旦你在$ .post()里面,你就会失去这个上下文。
在$ .post之前,将上下文保存在该保存按钮功能内的变量中。
在$ .post之前,将上下文保存在该保存按钮功能内的变量中。
- $('#dialog-form').dialog({
- // .....
- buttons: {
- 'save': function() {
- var $this = $(this);
- // -this- is still the original context
- // of $("#dialog-form")
- $.post({
- /// ...
- $this.dialog('close'); // <-- used here
- });
- }
- }
- });