簡體   English   中英

jQuery插件范圍問題

[英]jQuery plugin scope issue

在此jQuery插件中,我通過范圍解析忽略了某些內容。 這是我要實現的簡化示例:

(function($) {
    $.fn.dashboard = function(options) {
        this.onClick = function(e) {
            alert("do something");
            return false;
        };

        var createButton(parent) {
            //This should call the onClick method defined above when the link is clicked.
            var button = $('<a href="#">Reply</a>').click(this.onClick);
            parent.append(button);
        };

        return this.each(function() {
            var doc = $('body');
            createButton(doc);
        });
    };
})(jQuery);

問題是onClick永遠不會被調用。 絕對是某種范圍問題。

在插件內部, this指向jQuery對象。 您代碼中的問題是this.onClick ,它剛剛向jQuery對象添加了新屬性onClick

嘗試這個。

(function($) {
    $.fn.dashboard = function(options) {
        var doSomething = function(){
            alert("do something");
            return false;
        };

        var createButton(parent) {
            parent.append($('<a href="#">Reply</a>').click(doSomething));
        };

        return this.each(function() {
            var doc = $('body');
            createButton(doc);
        });
    };
})(jQuery);

this將是一個jQuery對象包裹匹配元件。 您可以遍歷該集合並分配給onClick ,或者(更正確地說)您使用jQuery的click事件處理程序,而不是直接分配給onClick

$.fn.dashboard = function(options) {
    this.each(function () {
        $(this).click(function(e) {

        });
    });
}

您應該閱讀jQuery頁面Plugins / Authoring

在您的示例中,createButton方法中的“ this”實際上是指createButton函數本身,而不是傳遞給插件的jQuery集合。

要使此工作有效,只需在plugin方法中將“ this”分配給變量,然后在您的createButton(和其他)函數中使用該變量。

(function($) {
    $.fn.dashboard = function(options) {

        var $this = this;

        this.onClick = function(e) {
            alert("do something");
            return false;
        };

        var createButton = function(parent) {
            //This should call the onClick method defined above when the link is clicked.
            var button = $('<a href="#">Reply</a>').click($this.onClick);
            parent.append(button);
        };

        return this.each(function() {
            var doc = $('body');
            createButton(doc);
        });
    };
})(jQuery);

請注意 ,此答案僅涉及范圍解析,實際上,正如該答案所提到的,您可能應該直接分配click函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM