2

私は次のコードを持っています:

var Modal = Class.extend({
    //--- Default options
    defaults: {
        width: 300,
        height: 200
        // . . . more options
    },

    //--- Initialize the Modal class
    init: function (options) {
        //--- Extend defaults and options
        this.options = jQuery.extend(this.defaults, options);
    },

    //--- Create the Modal
    create: function () {

            // . . . code removed

            var closeButton = document.createElement("div");
            jQuery(closeButton)
                .attr({ "class": "modal_close" })
                .css({ "cursor": "pointer" })
                .live("click", function () {
                    this.closeModal();
                })
                .appendTo(modalHead);

            // . . . more code
    },

    //--- Hide the Modal
    closeModal: function () {
        // TODO : Code to hide the modal
        jQuery("#modal_container").fadeOut(200).remove();
        jQuery("#lean_overlay").fadeOut(200).remove();
    }
});

create メソッドのクリック イベントで delete メソッドを呼び出そうとすると、次のエラーが発生します。

this.closeModal(); is not a function

ここで何が欠けていますか?

編集:私の質問を単純化するために、非表示機能をcloseModalに変更しました

4

3 に答える 3

9

this.hide();と置き換えます$(this).hide();

後で編集:

this入力する前に参考にしてください.live()

create: function () {
        // . . . code removed

        var closeButton = document.createElement("div");
        var myModal = this; 
        jQuery(closeButton)
            .attr({ "class": "modal_close" })
            .css({ "cursor": "pointer" })
            .live("click", function () {
                myModal.closeModal();
            })
            .appendTo(modalHead);

        // . . . more code
},
于 2012-11-21T14:44:49.827 に答える
0

この問題は、jQuery が、イベントが発生した DOM 要素を にバインドしたという事実から発生しthisます。これを回避するには、次を使用します

.live('click', this.closeModal)

の現在のインスタンスへの参照をキャッシュしたい場合はModal、次のinit functionようにすることができます。

init: function () {
    this.me = this;
}

参照するときは、使用することを忘れthis.meないでください( だけではありませんme)。

于 2012-11-21T14:48:15.043 に答える
0

試す:

.live('click', $.proxy(this, 'hide'))
于 2012-11-21T14:52:48.707 に答える