简体   繁体   English

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

[英]Cannot reference methods on my JQuery prototype class

I'm defining the behaviour for my content_item elements like this: 我正在为我的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();
        });

    }

I then apply makeContentItem with: 然后,我将makeContentItem应用于:

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

Clicking a content_item element generates this error: 单击content_item元素会产生此错误:

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

You added the method to a jQuery collection, then discarded that jQuery collection. 您将方法添加到jQuery集合中,然后丢弃了该jQuery集合。 Instead, you should to add it to the elements data structure and reference it from that. 相反,您应该将其添加到elements数据结构中并从中引用它。

$.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);
    });

}

or better yet, just make it a private function. 甚至更好,只需将其设为私有功能即可。

$.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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM