0

ダイアログという名前のオブジェクトを作成しようとしています。アイデアは、いくつかの関数を作成し、別のメソッド自体の内部でそれらを呼び出すことです。見てみましょう:

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()メソッドがトリガーされたため、削除する必要があります。しかし、うまくいきません。正しい方向に私を向けることができますか?

4

1 に答える 1

1

this宣言で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"
        });
    };  
}  
于 2012-08-14T21:03:28.370 に答える