无法引用我的 JQuery 原型类上的方法

Cannot reference methods on my JQuery prototype class

本文关键字:方法 原型 JQuery 引用 我的      更新时间:2023-09-26

我像这样定义content_item元素的行为:

    $.fn.makeContentItem = function() {
        $(this).selectItem = function() {
            $(".content_item").removeClass("selected");
            $(this).addClass("selected");
            console.log($(this).css('width'));
        }
        $(this).click(function(event) {
            console.log($(this));
            $(this).selectItem();
        });
    }

然后,我将makeContentItem应用于:

$(".content_item").makeContentItem();

单击 content_item 元素会生成此错误:

Uncaught TypeError: Object [object Object] has no method 'selectItem'

您将该方法添加到 jQuery 集合,然后丢弃该 jQuery 集合。相反,您应该将其添加到元素数据结构中并从中引用它。

$.fn.makeContentItem = function() {
    this.data("selectItem",function() {
        $(".content_item").removeClass("selected");
        $(this).addClass("selected");
        console.log($(this).css('width'));
    });
    this.click(function(event) {
        console.log($(this));
        $(this).data("selectItem").call(this);
    });
}

或者更好的是,让它成为一个私人功能。

$.fn.makeContentItem = function() {
    var selectItem = function() {
        $(".content_item").removeClass("selected");
        $(this).addClass("selected");
        console.log($(this).css('width'));
    };
    this.click(function(event) {
        console.log($(this));
        selectItem.call(this);
    });
    // and to make it a complete plugin, return this.
    return this;
}