jquery ui:在初始化之前不能调用对话框中的方法;尝试调用方法“close”

前端之家收集整理的这篇文章主要介绍了jquery ui:在初始化之前不能调用对话框中的方法;尝试调用方法“close”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用jquery ui对话框,我从jquery ui网站下载它,版本是jquery-ui-1.10.2.custom.min.js,jquery是jquery-1.9.1.js,它与jquery ui js捆绑在一起,但是现在我遇到一个问题:打开对话框并点击保存按钮,我想要关闭对话框,这里是我的代码
  1. $(function(){
  2. $("#dialog-form").dialog({
  3. autoOpen: false,height: 350,width: 450,modal: true,buttons: {
  4. "save": function() {
  5. if(!checkDept()){
  6. return ;
  7. }
  8. $.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){
  9. if(status == 'success'){
  10. alert('save success');
  11. $(this).dialog("close");
  12. }else{
  13. alert('error:'+data);
  14. }
  15. },"json");
  16. }
  17. },close: function() {
  18. $(this).dialog("close");
  19. }
  20. });
  21.  
  22. /* to open dialog*/
  23. $("#add").click(function(){
  24. $("#dialog-form").dialog("open");
  25. });

现在当我关闭“保存成功”弹出对话框时,对话框对话框未关闭,并发生错误

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之前,将上下文保存在该保存按钮功能内的变量中。
  1. $('#dialog-form').dialog({
  2. // .....
  3. buttons: {
  4. 'save': function() {
  5.  
  6. var $this = $(this);
  7. // -this- is still the original context
  8. // of $("#dialog-form")
  9.  
  10. $.post({
  11. /// ...
  12. $this.dialog('close'); // <-- used here
  13. });
  14. }
  15. }
  16. });

猜你在找的jQuery相关文章