2012-08-14 67 views
0

我想要创建一个名为的对象Dialogo。这个想法是创建一些函数,然后在另一个方法本身内部调用它们。看看:方法不是在另一个方法里面调用

function Dialogo(tamano){ 
    this.tamano = tamano; 

    this.cerrar = function(){ 
     $('#dialogo_fondo').remove(); 
    }; 

    this.mostrar = function(){ 
     var dialogo_fondo = $('<div>').attr({id: 'dialogo_fondo' }); 
     $('body').fadeIn("slow", function(){$(this).append(dialogo_fondo);}); 
     $('#dialogo_fondo').css({"width": $(window).width(), "height": $(window).height()}); 
     $('#dialogo_fondo').click(function(){ 
      this.cerrar(); 
     }); 
    }; 
} 

使用jquery 1.7.2。根据代码,当我点击#dialogo_fondo元素时,应该将其删除,因为cerrar()方法在点击事件中被触发。但它不起作用。你能指点我正确的方向吗?

回答

1

this in mostrar声明指向匿名函数实例,请用console.log(this);进行检查。所以你需要创建另一个对外部对象var that = this;的引用,并用它代替:

function Dialogo(tamano){ 
    var that = this; // <--- here is the magic 

    this.tamano = tamano; 

    this.cerrar = function(){ 
     $('#dialogo_fondo').remove(); 
    }; 

    this.mostrar = function(){ 
     var dialogo_fondo = $('<div>').attr({id: 'dialogo_fondo' }); 
     $('body').fadeIn("slow", function(){$(this).append(dialogo_fondo);}); 
     $('#dialogo_fondo').css({"width": $(window).width(), "height": $(window).height()}); 
     $('#dialogo_fondo').click(function(){ 
      that.cerrar(); // <---- use "that", not "this" 
     }); 
    }; 
} 
+0

你就像哈利波特......运用魔法!非常感谢! – manix 2012-08-14 21:10:37

+0

@manix:我希望你明白了为什么你以前的解决方案不起作用 – zerkms 2012-08-14 21:12:30

+0

是的,我真的是js中的新手,但我明白了!有一些这样的技巧,我需要记住进一步 – manix 2012-08-14 21:14:07