jQuery插件:如何从事件中访问?

时间:2013-12-23 01:15:49

标签: jquery jquery-plugins jquery-events

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

(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运行时错误:对象不支持属性或方法   '数据'

访问不在事件中的插件数据+方法可以正常工作。

1 个答案:

答案 0 :(得分:0)

试试这个:

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

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

相关问题