【问题标题】:jQuery Plugin: how to access from an event?jQuery 插件:如何从事件中访问?
【发布时间】:2023-04-10 12:31:01
【问题描述】:

假设我有这个非常基本的插件:

(function ($) {

"use strict";

// Namespaced methods.
var methods = {
    init: function (options) {

        return this.each(function () {

            // Default settings.
            var defaults = {
                'sampleText': 'hello'
            };

            var $this = $(this);
            var data = $this.data('me');

            // Continue if the plugin hasn't been initialized yet.
            if (!data) {

                $this.mouseup(function () {
                    $this.trigger('onClick'); // events.
                });

                // Add control data.
                $this.data('me', defaults);
                $this.trigger('onLoad'); // events.

            }

        });

    },

    isPlugin: function() {
        return true;
    },

    getData: function() {
        return $(this).data('me');
    }

$.fn.tester = function (method) {

    // Method calling logic.
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' + method + ' does not exist on jQuery.test');
    }

};

})(jQuery);

然后我像这样应用插件并监控点击事件:

$('#poo').tester();
$('#poo').on('onClick', function (e) {
    var $data = e.target.tester('isPlugin');
    var dat = e.target.data('me');
});

问题是;在事件处理中,我无法再次访问该插件。试图在 Visual Studio 中获取这两个数据的结果告诉我

JavaScript 运行时错误:对象不支持属性或方法 '测试者'

还有……

JavaScript 运行时错误:对象不支持属性或方法 '数据'

访问不在事件内部的插件数据+方法工作正常。

【问题讨论】:

    标签: jquery jquery-plugins jquery-events


    【解决方案1】:

    试试这个:

    var $data = $(e.target).tester('isPlugin');
    var dat = $(e.target).data('me');
    

    e.target 本身引用了一个 DOM 节点,您实际上需要一个正在使用您的插件的 jQuery 对象。

    【讨论】:

    • 谢谢查理——成功了。虽然它必须是一些简单的我错过了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2015-03-06
    • 2019-01-30
    相关资源
    最近更新 更多